




Sponsored
Sponsored
This approach uses two pointers: one to track the position for the next non-zero element and the other to iterate through the array. We move all non-zero elements to the beginning of the array using these two pointers and fill the remaining positions with zeroes.
Time Complexity: O(n), where n is the length of the array. We make a single pass through the array.
Space Complexity: O(1), as we perform the operation in place.
1#include <stdio.h>
2
3void moveZeroes(int* nums, int numsSize) {
4    int lastNonZeroFoundAt = 0;
5    for (int i = 0; i < numsSize; i++) {
6        if (nums[i] != 0) {
7            nums[lastNonZeroFoundAt++] = nums[i];
8        }
9    }
10    for (int i = lastNonZeroFoundAt; i < numsSize; i++) {
11        nums[i] = 0;
12    }
13}The code defines a function moveZeroes that takes an array nums and its size numsSize. The function maintains a pointer lastNonZeroFoundAt to keep track of the position to place the next non-zero element. As we iterate through nums, we shift non-zero elements to the front and then fill the remaining elements with zeroes.
This method uses a two-pointer technique where we place one pointer at the beginning of the array and the other to iterate through the array. Whenever we encounter a non-zero element, we swap it with the first pointer's position, allowing us to effectively move zeroes to the end by swapping.
Time Complexity: O(n), single iteration with swaps.
Space Complexity: O(1), in-place swaps.
1public class Solution {
2    public void MoveZeroes(int[] nums) {
        int j = 0;
        for (int i = 0; i < nums.Length; i++) {
            if (nums[i] != 0) {
                int temp = nums[j];
                nums[j] = nums[i];
                nums[i] = temp;
                j++;
            }
        }
    }
}This C# solution uses a swap logic similar to the C solution, incrementing j every time a non-zero element is swapped to the front.