DSA interview question
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.
int longestOnes(const vector<int>& nums, int k);
Input (nums, k) | Output | Explanation |
|---|---|---|
([1,1,1,0,0,0,1,1,1,1,0], 2) | 6 | Flip 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) | 0 | No flips allowed |
([1,1,1], 0) | 3 | |
([0,0,0,1], 4) | 4 | k may exceed the number of zeros |
(Confirm: values are 0 or 1; flipping is optional; the answer is a length of contiguous elements.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in