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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay