Approach: The optimal solution uses the two-pointer technique. One pointer keeps track of the position where the next non-zero element should be placed, while the other pointer iterates through the array. Whenever a non-zero element is encountered, it is swapped with the element at the target position and the target position is advanced.
This approach performs the operation in-place without using any additional array and ensures that the original ordering of non-zero elements remains unchanged.
Java Solution:
public class MoveZeroes {
public static void moveZeroes(int[] numbers) {
int insertPosition = 0;
for (int currentIndex = 0; currentIndex < numbers.length; currentIndex++) {
if (numbers[currentIndex] != 0) {
int temp = numbers[insertPosition];
numbers[insertPosition] = numbers[currentIndex];
numbers[currentIndex] = temp;
insertPosition++;
}
}
}
public static void main(String[] args) {
int[] numbers = {0, 1, 0, 3, 12};
moveZeroes(numbers);
for (int number : numbers) {
System.out.print(number + " ");
}
}
}Output: 1 3 12 0 0
Time Complexity: O(n), where n is the number of elements in the array. The array is traversed only once.
Space Complexity: O(1), since the rearrangement is performed in-place without using extra memory proportional to the input size.
Key Interview Points: • The two-pointer technique provides an optimal in-place solution. • The relative order of non-zero elements is preserved, which is an important requirement of the problem. • An alternative approach is to create a new array and copy non-zero elements first, but that requires O(n) additional space.