Move Zero's Problem - Understanding syntax choices and logic

Hi all, I found a working and efficient solution to a problem but without an explanation, and I'm trying to make sense of it. I understand the problem, but I'm a bit confused by how the solution code works. Any help appreciated.

Problem: Given an 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.
Example: Input: [0,1,0,3,12] Output:[1,3,12,0,0]

My questions:
1. Why the j++ in nums[j++] = nums[i];? What is it accomplishing?
2. What does the semicolon mean before j in ;j < nums.size()?

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int j = 0;
        // move all the nonzero elements advance
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                nums[j++] = nums[i];
            }
        }
        for (;j < nums.size(); j++) {
            nums[j] = 0;
        }
    }
};


Thanks!!
Last edited on
Why the j++ in nums[j++] = nums[i];? What is it accomplishing?
It's equivalent to this:
1
2
nums[j] = nums[i];
j = j + 1;

What does the semicolon mean before j in ;j < nums.size()?
The for syntax is
 
for (/*initialization*/; /*condition*/; /*increment*/) /*body*/
The semicolons don't mean anything, it's just what the syntax requires.
Hello beulette,

The for loop has 3 parts as helios has pointed out. The (;) is what separates the 3 parts. On an occasion you might see a for loop like for (;;). This means that the for loop does not "initialize" or check any condition or increase any counter, but the (;)s still have to be there.

In the line for (;j < nums.size(); j++) it is using the last value of "j" from the last for loop, so you do not need the "initialization" first part here, but "j" is pointing to the correct element of the array to put the zeros.

Another way to look at j++ is as a postfix it means to use the value of "j" first then add 1 when finished. The opposite is the prefix which means add 1 before you use the variable. And the same is true if you use the (--) to subtract 1.

In the end the j++ is a way of keeping track of what the next element of the array is when the for loop ends so that you will know where to start putting the zeros.

Andy
An efficient solution to this problem is provided in the standard library under the name std::remove.
Topic archived. No new replies allowed.