Sobes.tech
Senior

Algorithmic problem: given an integer array, move all zeros to the end, preserving the order of other elements (e.g., [1,0,3,0,1] → [1,3,1,0,0])

sobes.tech AI

Answer from AI

The task is to move all zeros to the end of the array while preserving the order of the other elements. The solution can be done in one pass using two pointers.

Example in Java:

public class MoveZeros {
    public static void moveZerosToEnd(int[] nums) {
        int insertPos = 0; // position to insert non-zero element
        
        for (int num : nums) {
            if (num != 0) {
                nums[insertPos++] = num;
            }
        }
        
        while (insertPos < nums.length) {
            nums[insertPos++] = 0;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 0, 3, 0, 1};
        moveZerosToEnd(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
        // Output: 1 3 1 0 0 
    }
}

Idea:

  • Iterate through the array, copying all non-zero elements to the front.
  • Then fill the remaining positions with zeros.

Complexity: O(n), additional space: O(1).