Move zeros to the front
Company: Uber
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: 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.
Read the full Uber Data Scientist interview experience this question came from
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.
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.
Community answers
Answer by daow