Move Zeros to the Front with Two Pointers
Problem statement
Move every zero in an integer array to the beginning. The relative order of nonzero values need not be preserved.
For this exercise, use this deterministic two-pointer rule: repeatedly swap the leftmost nonzero value with the rightmost zero strictly to its right. Stop when no such pair remains. Return the resulting array.
For example, the reported interview input [1,0,5,6,0,2,0] can become [0,0,0,5,2,6,1]. The specified practice swaps instead produce [0,0,0,6,5,2,1]; both satisfy the reported move-zero objective.
Function
moveZerosToFront(nums: int[]) → int[]Examples
Example 1
nums = [1,0,5,6,0,2,0]return = [0,0,0,6,5,2,1]Swap the leftmost 1 with the last zero, then swap 5 with the remaining rightmost zero.
Example 2
nums = [0,4,0,-2,9]return = [0,0,4,-2,9]The first zero is already at the front. Swap 4 with the zero at index 2.
Example 3
nums = [2,3,4]return = [2,3,4]No zero exists, so the array stays unchanged.
Constraints
0 <= nums.length <= 100000.-1000000000 <= nums[i] <= 1000000000.- The two-pointer algorithm uses constant working variables; language-level input and return copies are outside this bound.