-
-
Notifications
You must be signed in to change notification settings - Fork 78
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
coding_interviews/algoexpert/move-element-to-end/move-element-to-end.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/** | ||
* 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. | ||
* | ||
* Input: | ||
* array = [2, 1, 2, 2, 2, 3, 4, 2] | ||
* toMove = 2 | ||
* | ||
* Output: | ||
* [1, 3, 4, 2, 2, 2, 2, 2] | ||
*/ | ||
|
||
function moveElementToEnd(array, toMove) { | ||
let count = 0; | ||
let pointer = 0; | ||
|
||
for (let index = 0; index < array.length; index++) { | ||
if (array[index] === toMove) count++; | ||
else { | ||
array[pointer] = array[index]; | ||
pointer++; | ||
} | ||
} | ||
|
||
for (let index = pointer; index < array.length; index++) { | ||
array[index] = toMove; | ||
} | ||
|
||
return array; | ||
} |