DSA interview question
An ad-tracking system logs each second as 1 (a click happened) or 0 (no click), and analysts want the number of contiguous time ranges with exactly goal clicks. "Exactly" is awkward for a sliding window, but "at most" is easy: since values are non-negative, the window sum only grows as it widens. So compute atMost(goal) − atMost(goal − 1), where atMost(g) counts subarrays with sum ≤ g by adding, for each right end, the number of valid starts.
Example: [1, 0, 1, 0, 1], goal = 2 → 4.
long long numSubarraysWithSum(const vector<int>& nums, int goal); // nums[i] is 0 or 1
Input (nums, goal) | Output | Explanation |
|---|---|---|
([1, 0, 1, 0, 1], 2) | 4 | [1,0,1], [1,0,1,0], [0,1,0,1], [1,0,1] |
([0, 0, 0, 0, 0], 0) | 15 | Every subarray: 5 · 6 / 2 |
([1, 1, 1], 2) | 2 | |
([0, 1, 0], 1) | 4 | |
([1, 0, 1], 5) | 0 |
(Confirm: subarrays are non-empty and contiguous; values are 0/1; the count can be about n²/2, so use 64-bit.)
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