Skip to content

Commit 27c4596

Browse files
committed
rename to move elements to end
1 parent 223ada1 commit 27c4596

File tree

2 files changed

+37
-28
lines changed

2 files changed

+37
-28
lines changed

Arrays/move_element_to_end.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Move 0's to end
3+
Sample Input : [1, 0, 3, 0, 0, 5]
4+
Output : [1, 3, 5, 0, 0, 0]
5+
6+
This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input,
7+
and returns a modified array with all instances of toMove moved to the end of the array.
8+
9+
The function first initializes an integer variable index to 0, which will keep track of the index of the first
10+
element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the
11+
current element is not equal to toMove, it replaces the element at the index position with the current element
12+
and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the
13+
beginning of the array.
14+
15+
Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in
16+
the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the
17+
end of the array.
18+
19+
Finally, the modified array is returned.
20+
21+
O(n) time | O(1) space - where n is the length of the array
22+
*/
23+
#include <vector>
24+
25+
std::vector<int> MoveElementToEnd(std::vector<int>& array, int toMove) {
26+
int index = 0; // initialize a variable to keep track of the index where elements should be moved to
27+
for (int i = 0; i < array.size(); i++) { // loop through the entire array
28+
if (array[i] != toMove) { // check if the current element is not equal to the element to be moved
29+
array[index] = array[i]; // move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array[i])
30+
index++; // increment the index variable by 1 to keep track of the index where the next non-target element should be moved
31+
}
32+
}
33+
for (int i = index; i < array.size(); i++) { // loop through the remaining elements in the array from index to the end
34+
array[i] = toMove; // set each element to be the target element
35+
}
36+
return array; // return the modified array
37+
}

Arrays/move_zeros.cpp

-28
This file was deleted.

0 commit comments

Comments
 (0)