DEV Community

Cover image for move all instances of that target value to the end end of the array
chandra penugonda
chandra penugonda

Posted on Edited on

move all instances of that target value to the end end of the array

This problem was asked by Intel.

You are given an array and a target value, move all instances of that target value to the end end of the array

Example

function moveElement(arr, val){

};

// testcase
const arr = [2, 1, 2, 2, 2, 3, 4, 2];
console.log(moveElement(arr, 2)); // [4, 1, 3, 2, 2, 2, 2, 2]
Enter fullscreen mode Exit fullscreen mode

Explanation : All the occurences of 2 are moved at the end of the array.

Solution

function moveElement(arr, val) {
  let i = 0,
    j = arr.length - 1;

  while (i < j) {
    while (i < j && arr[j] === val) {
      j--;
    }
    if (arr[i] === val) {
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    i++;
  }
  return arr
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Initialize i and j pointers at both ends of the array.
  • Loop while i is less than j:
  • Shift j leftwards until we find a non-target value.
  • If arr[i] is the target, swap it with arr[j].
  • Increment i towards right.
  • This continues until i crosses j, which means all target values are at the end.
  • So this approach efficiently moves the target values to the end in a single pass. The swap operation keeps the original order intact.

Top comments (0)