Shift Non-Zero Elements Left In Place
Company: J.P. Morgan
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question tests a candidate's ability to perform in-place array manipulation while preserving element order, evaluating practical understanding of the two-pointer technique and space complexity constraints. It falls under array and algorithm fundamentals, commonly asked to assess whether engineers can operate within O(1) extra space and O(n) time bounds on partition-style problems.
Constraints
- 1 <= nums.length <= 10^5
- -2^31 <= nums[i] <= 2^31 - 1
- Must operate in place with O(1) extra space
- Target O(n) time, at most two passes
Examples
Input: ([0, 1, 0, 3, 12],)
Expected Output: [1, 3, 12, 0, 0]
Explanation: Non-zero elements 1, 3, 12 keep their order; the two zeros move to the end.
Input: ([0],)
Expected Output: [0]
Explanation: Single zero stays in place.
Input: ([5, 0, 0, 7, 0, 11],)
Expected Output: [5, 7, 11, 0, 0, 0]
Explanation: Non-zeros 5, 7, 11 preserved; three zeros pushed to the back.
Input: ([1, 2, 3],)
Expected Output: [1, 2, 3]
Explanation: No zeros, so the array is unchanged.
Input: ([0, 0, 0],)
Expected Output: [0, 0, 0]
Explanation: All zeros; the array remains the same.
Input: ([-1, 0, -2, 0, 3],)
Expected Output: [-1, -2, 3, 0, 0]
Explanation: Negative non-zero values are handled the same way; -1, -2, 3 keep order and zeros go to the end.
Input: ([42],)
Expected Output: [42]
Explanation: Single non-zero element is unchanged.
Hints
- Maintain a write pointer that tracks the position where the next non-zero element should go.
- Walk through the array with a read pointer; whenever you hit a non-zero value, swap it into the write-pointer slot and advance the write pointer.
- Swapping (rather than overwriting) automatically pushes the zeros toward the back while keeping the non-zero order intact, and it keeps everything in O(1) extra space.