Search⌘ K
AI Features

Move All Zeros to the Beginning of the Array

Explore how to move all zeros in an integer array to the beginning while preserving the relative order of non-zero elements. Understand and implement a space-efficient O(1) in-place algorithm using Read and Write pointers that operates in O(n) time. This lesson equips you with a fundamental array manipulation technique valuable for coding interviews and problem-solving.

Statement

We’re given an integer array, nums. Move all zeroes, if any, to the left while maintaining the order of other elements in the array. All changes must be made in nums itself; no return value is expected.

Example

Let’s look at the following integer array:

g array 0 1 2 3 4 5 6 7 8 1 10 20 0 59 63 0 88 0

After moving all zeros to the left, the array should look like this:

g array 0 1 2 3 4 5 6 7 8 0 0 0 1 10 20 59 63 88

Note: We need to maintain the order of non-zero elements.

Sample input

[1, 10, 20, 0, 59, 63, 0, 88, 0]

Expected output

[0, 0, 0, 1, 10, 20, 59, 63, 88]

Try it yourself #

#include <iostream>
#include <vector>
using namespace std;
void MoveZerosToLeft(vector<int> &nums) {
return;
}

Solution

We will use Read and Write ...