
Problem
Solution
Submissions
Move Zeroes
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to move all zeros to the end of an array. Given an integer array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array.
Note that you must modify the array in-place and not allocate extra space for another array.
Example 1
- Input: nums = [0,1,0,3,12]
- Output: [1,3,12,0,0]
- Explanation:
We need to move all zeros to the end while keeping the order of non-zero elements.
Starting with [0,1,0,3,12], after moving all non-zero elements to the front and filling the rest with zeros, we get [1,3,12,0,0].
Example 2
- Input: nums = [0]
- Output: [0]
- Explanation:
Array contains only one element which is already 0.
No changes needed as zero is already at the end.
Constraints
- 1 ≤ nums.length ≤ 10^4
- -2^31 ≤ nums[i] ≤ 2^31 - 1
- You must perform operations in-place with O(1) extra memory
- 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 approach to solve this problem
- Keep track of the position where the next non-zero element should be placed
- Iterate through the array, moving non-zero elements to their correct positions
- After placing all non-zero elements, fill the remaining positions with zeros
- Make sure you don't create unnecessary swaps if the element is already in the correct position