Move Element to End

A corgi smiling happily

You’re given an array of integers and an integer. Write a function that moves all instances of that integer in the array to the end of the array and returns the array.

The function should perform this in place (i.e., it should mutate the input array) and doesn’t need to maintain the order of the other integers.

Sample Input

1array = [2, 1, 2, 2, 2, 3, 4, 2]
2toMove = 2

Sample Output

1[1, 3, 4, 2, 2, 2, 2, 2] // the numbers 1, 3, and 4 could be ordered differently

Hints

Hint 1

You can solve this problem in linear time.

Hint 2

In view of Hint #1, you can solve this problem without sorting the input array. Try setting two pointers at the start and end of the array, respectively, and progressively moving them inwards.

Hint 3

Following Hint #2, set two pointers at the start and end of the array, respectively. Move the right pointer inwards so long as it points to the integer to move, and move the left pointer inwards so long as it doesn’t point to the integer to move. When both pointers aren’t moving, swap their values in place. Repeat this process until the pointers pass each other.

Optimal Space & Time Complexity

O(n) time | O(1) space - where n is the length of the array

Solution-1
1function moveElementToEnd(array, toMove) {
2 let count = 0;
3 let arrLen = array.length;
4
5 while (count < arrLen) {
6 if (array[count] == toMove) {
7 array.splice(count, 1)
8 array.push(toMove)
9 arrLen--;
10 } else {
11 count++;
12 }
13 }
14
15 return array
16}
Solution-2
1function moveElementToEnd(array, toMove) {
2 let count = 0;
3 let arrLen = array.length - 1;
4
5 while (count < arrLen) {
6 while (count < arrLen && array[arrLen] === toMove) arrLen--;
7 if (array[count] === toMove) swap (count, arrLen, array);
8 count++
9 }
10
11 return array
12}
13
14function swap(i, j, array) {
15 const temp = array[j]
16 array[j] = array[i]
17 array[i] = temp
18}

🏅

Do you have any questions, or simply wish to contact me privately? Don't hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.