
Problem
Solution
Submissions
Move Zeroes to End
Certification: Basic Level
Accuracy: 66.67%
Submissions: 3
Points: 5
Write a Java program to move all zeroes in an array to the end while maintaining the relative order of the non-zero elements. The operation should be done in-place with minimal operations.
Example 1
- Input: nums = [0, 1, 0, 3, 12]
- Output: [1, 3, 12, 0, 0]
- Explanation:
- Step 1: Maintain a pointer for the position where next non-zero element should be placed.
- Step 2: Iterate through the array. When a non-zero element is found, place it at the pointer position.
- Step 3: After all non-zero elements are positioned correctly, fill the remaining positions with zeroes.
- Step 4: The array now has all zeroes at the end while preserving the order of non-zero elements.
Example 2
- Input: nums = [0, 0, 1]
- Output: [1, 0, 0]
- Explanation:
- Step 1: Maintain a pointer for the position where next non-zero element should be placed.
- Step 2: Iterate through the array. The only non-zero element 1 is placed at index 0.
- Step 3: Fill the remaining positions (indices 1 and 2) with zeroes.
- Step 4: The array now has all zeroes at the end while preserving the order of non-zero elements.
Constraints
- 1 ≤ nums.length ≤ 10^4
- -2^31 ≤ nums[i] ≤ 2^31 - 1
- You must do this in-place without making a copy of the array
- Minimize the total number of operations
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a two-pointer technique to solve this problem
- Keep track of the position where the next non-zero element should be placed
- Iterate through the array once
- When you find a non-zero element, place it at the tracked position and increment the position
- After processing all elements, fill the remaining positions with zeroes