The problem is to move all zeros in a given integer array nums
to the end of the array while maintaining the relative order of the non-zero elements. The operation should be performed in-place.
Example:
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Q: Can the array contain negative numbers? A: Yes, the array can contain negative numbers.
Q: Are there any constraints on the array length? A: The array length can vary, but typically within the constraints of an integer array in memory.
Q: Do we need to return anything or modify the array in place? A: The array should be modified in place, and there’s no need to return anything.
lastNonZeroFoundAt
to keep track of the position of the last non-zero found.cur
to traverse the array.cur
. Whenever a non-zero element is found, swap it with the element at the lastNonZeroFoundAt
index and increment lastNonZeroFoundAt
.#include <vector>
void moveZeroes(std::vector<int>& nums) {
int lastNonZeroFoundAt = 0; // Pointer to keep track of last non-zero element found
// Move all non-zero elements forward
for (int cur = 0; cur < nums.size(); cur++) {
if (nums[cur] != 0) {
std::swap(nums[lastNonZeroFoundAt], nums[cur]);
lastNonZeroFoundAt++;
}
}
}
cur
pointer and occasionally perform swaps.lastNonZeroFoundAt
pointer to 0.cur
pointer.nums[cur] != 0
), swap it with the element at index lastNonZeroFoundAt
and increment lastNonZeroFoundAt
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?