Move Element

Given an array of integers and a target value, move all instances of that target value to the end end of the array. The order of the resulting array does not matter in this question.

Two Pointer Approach

  1. Declare two pointers left and right.
  2. left pointer is intialized to the 0th index. The right pointer is initialized to the last index of the array.
  3. The job of the left pointer is to check if the value at the left index is EQUAL to the target value.
  4. Run a while loop while left < right. If arr[left] is equal to the target value - This means we found a target value that needs to be at the end of the array.
  5. Since we have the right pointer initialized to the end of the array, we swal the arr[left] and arr[right] values. Essentially taking the target value at the end. After swapping, we decrement the right pointer, because we might encounter more such target values that need to be at the end.
  6. If the left value is not equal to the target value, we simply increment the left pointer.

Time complexity

  • O(n) Since we are iterating the array only once.
Solve Move Element on Algochurn

Practice all the solutions below

Practice the most popular front-end questions asked in coding interviews with   Frontend Churn