Move zeros to the front
Company: Uber
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates array manipulation skills, in-place algorithm design, and reasoning about time and space complexity while preserving element order under an O(1) extra space constraint.
Constraints
- 0 <= len(nums) <= 100000
- -1000000000 <= nums[i] <= 1000000000
- The operation must use O(1) extra space
Examples
Input: [1, 0, 2, 0, 3]
Expected Output: [0, 0, 1, 2, 3]
Explanation: The two zeros move to the front, and the non-zero values 1, 2, 3 keep their original order.
Input: [0, 0, 1, 2]
Expected Output: [0, 0, 1, 2]
Explanation: Zeros are already at the front, so the array stays the same.
Input: [1, 2, 3]
Expected Output: [1, 2, 3]
Explanation: There are no zeros to move.
Input: [0, 0, 0]
Expected Output: [0, 0, 0]
Explanation: All elements are zero, so the array remains unchanged.
Input: []
Expected Output: []
Explanation: An empty array should return an empty array.
Input: [-1, 0, -2, 0, 3]
Expected Output: [0, 0, -1, -2, 3]
Explanation: Zeros move to the front, and the non-zero values -1, -2, 3 keep their relative order.
Hints
- Try processing the array from right to left and placing non-zero values at the end.
- Once all non-zero values are in their final relative order, fill the remaining positions at the front with 0.