Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Alternate C++ Solution - keep track of zeros

Roberto Pantoja

Jun 15, 2023

Instead of keeping track of the 1s, it might be more intuitive to follow the zeros.

Here's one way to do this.

static int findLength(const vector<int> &arr, int k) { int maxLength = 0, start = 0, tempK = 0; for(int end = 0; end < arr.size(); end++){ if(arr[end] == 0) tempK++; // If there are too many zeros, increment start while(tempK > k){ if(arr[start++] == 0) tempK --; } maxLength = max(maxLength, end - start + 1); } return maxLength; }

Anyone else approach the problem like this?

0

0

Comments
Comments
A
Alfonso Vieyra2 years ago

I did yes, you can actually change the while loop into an if statement since we're only concerned with the maximum.

 James
Jamesa year ago

I solved it the same way as you did. I found this to be much easier to understand. I am still not sure why keeping track of the 1's is a better solution.

On this page