PPractick

DSA interview question

Max Consecutive Ones III

Medium · Algorithms · Topics: sliding window, array

The problem

A factory's uptime log is a binary array (1 = machine running, 0 = down). Maintenance can retroactively "fix" up to k down periods. What's the longest stretch of consecutive 1s achievable after flipping at most k zeros? Rephrased: find the longest window containing at most k zeros. A sliding window handles it: extend the right end, count zeros, and whenever the count exceeds k, shrink from the left until it's back to k.

Example: [1,1,1,0,0,0,1,1,1,1,0], k = 2 → 6.

Function signature

int longestOnes(const vector<int>& nums, int k);

Test cases

Input (nums, k)OutputExplanation
([1,1,1,0,0,0,1,1,1,1,0], 2)6Flip the last two 0s
([0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], 3)10
([0,0,0], 0)0No flips allowed
([1,1,1], 0)3
([0,0,0,1], 4)4k may exceed the number of zeros

(Confirm: values are 0 or 1; flipping is optional; the answer is a length of contiguous elements.)

How interviewers phrase it

Clarifying questions to ask

  1. At most k flips, not exactly k? (At most.)
  2. Can k be 0 or larger than the number of zeros? (Yes.)
  3. Is the input size large? (Up to 10⁵, so O(n).)

Follow-ups to expect

  1. "Why is it the longest window with at most k zeros?"
  2. "Why can the left pointer only move forward?"
  3. "Non-shrinking variant?"
  4. "Streaming version with a huge array?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in