0

I struggled with problem 1535 (Find the Winner of an Array Game) on LeetCode. I decided to use the top solution, which looked like this:

int getWinner(vector<int>& A, int k) {
    int cur = A[0], win = 0;
    for (int i = 1; i < A.size(); ++i) {
        if (A[i] > cur) {
            cur = A[i];
            win = 0;
        }
        if (++win == k) break;
    }
    return cur;
}

However, I implemented it like this:

class Solution {
public:
    int getWinner(vector<int>& arr, int k) {
        int win = arr[0];
        int numsWon = 0;
        
        for(int i = 1; i < arr.size(); i++) {
            if(arr[i] > win) {
                numsWon = 0;
                win = arr[i];
            }
            
            if(numsWon++ == k) break;
        }
        return win;
    }
};

The code didn't work until I switched the ++ operators. Does anyone know why?

  • Google 'c++ pre increment vs post increment' – Michael Surette Sep 20 '20 at 23:24
  • 3
    Does this answer your question? [Post-increment and Pre-increment concept?](https://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept) – dewaffled Sep 20 '20 at 23:25
  • Is it surprising that code stops working when you change it? If nothing else, this should tell you that `++win` and `win++` mean different things. They are similar, but in coding, changing one seemingly minor detail can break an entire system. – JaMiT Sep 21 '20 at 02:23

2 Answers2

1

for:

if (++win == k) break;    

The value of win is incremented by 1 first, and then is put though the comparison operator. It is the same as doing.

win = win + 1;  
if(win == k) break;  

where as when the ++ is after the win, it increments the value of win after the comparison like:

if(win == k){  
    win = win + 1;
    break;
}
rnorthby
  • 26
  • 1
0

++x happens prior to assignment (pre-increment), but x++ happens after assignment (post-increment). x++ executes the statement and then increments the value. ++x increments the value and then executes the statement.

Read about post and pre increment in c++.

Post and Pre increment gfg

What is the difference between pre-increment and post-increment in the cycle (for/while)?

Mohit Sharma
  • 338
  • 2
  • 13