easyArraysPattern: Two Pointers
Move Zeros to End Solution
Problem Statement
You are given an array of integers `arr`. Rearrange the elements in the array such that all zeros are moved to the end, while maintaining the relative order of non-zero elements.
Examples
Example 1:
Input:[0, 1, 0, 3, 12]
Output:[1, 3, 12, 0, 0]
Explanation: Non-zero elements are moved to the front in their original order, zeros are moved to the end
Example 2:
Input:[0, 0, 0, 0]
Output:[0, 0, 0, 0]
Explanation: If all elements are zeros, the array remains unchanged
Constraints
- 1 <= n <= 10^5
Time: O(N) Space: O(1)
Maintain a pointer 'lastNonZeroFoundAt'. Iterate array, if element is non-zero, swap it with element at 'lastNonZeroFoundAt' and increment the pointer. Time: O(N), Space: O(1).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
