Move Zeros To End(Java Solution)

Big_Dream_Coder
1 min readJun 15, 2022

a question on Pramp platform

In the beginning, the solution that I come up with is below. Using two pointers to find the non-zero element and set it at where the slow pointer points at, and then iterate the whole array. The slow pointer will return the last place that is not zero. Once I get the last place, I will set the rest of the array to zero and just return the result as the answer. TC: O(N) SC: O(N)

static int[] moveZeroes(int[] arr) {
int p = removeVal(arr, 0);
for(int i = p; i < arr.length; i++){
arr[i] = 0;
}
return arr;
}
static int removeVal(int[] nums, int val){
int slow = 0;
int fast = 0;
for(int i = 0; i < nums.length; i++){
if(nums[fast] != val){
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}

When I was practicing mock interview on Pramp, my interviewer did a little optimization to my code. This is a really great solution because I don’t need to redundantly set the rest of the array into zero instead swapping the element of the two pointers. TC: O(N) SC: O(N) but the time that this solution below is slightly faster than the code above.

static int[] moveZerosToEnd(int[] arr) {
// your code goes here
removeVal(arr, 0);
return arr;
}
static void removeVal(int[] arr, int val){
int slow = 0, fast = 0;
while(fast < arr.length){
if(arr[fast] != val){
int temp = arr[slow];
arr[slow] = arr[fast];
arr[fast] = temp;
slow++;
}
fast++;
}
}

--

--