💡 Using two counts with sliding windows yields exact count efficiently.
def numSubarraysWithSum(nums, goal):
def atMost(S):
count = left = 0 # STEP 1,13
current_sum = 0
for right, num in enumerate(nums): # STEP 2,4,6,8,10,14,16,18
current_sum += num # STEP 2,4,6,8,10,14,16,18
while current_sum > S: # STEP 10,18
current_sum -= nums[left] # STEP 11,19
left += 1 # STEP 11,19
count += right - left + 1 # STEP 3,5,7,9,11,15,17,19
return count # STEP 12,20
return atMost(goal) - atMost(goal - 1) if goal > 0 else atMost(0) # STEP 20
if __name__ == '__main__':
print(numSubarraysWithSum([1,0,1,0,1], 2)) # Output: 4
📊
Binary Subarrays With Sum - Watch the Algorithm Execute, Step by Step
Watching the algorithm step through each pointer movement and sum update reveals how the sliding window efficiently counts subarrays without enumerating all possibilities.
Step 1/20
·Active fill★Answer cell
expand
L ▼
1
0
0
1
1
2
0
3
1
4
Metric: 0
Answer: 0
expand
L=R
1
0
0
1
1
2
0
3
1
4
Window: [1]
Metric: 1
Answer: 1
record_answer
L=R
1
0
0
1
1
2
0
3
1
4
Window: [1]
Metric: 1
Answer: 1
expand
L ▼
1
0
R ▼
0
1
1
2
0
3
1
4
Window: [1, 0]
Metric: 1
Answer: 2
record_answer
L ▼
1
0
R ▼
0
1
1
2
0
3
1
4
Window: [1, 0]
Metric: 1
Answer: 3
expand
L ▼
1
0
0
1
R ▼
1
2
0
3
1
4
Window: [1, 0, 1]
Metric: 2
Answer: 6
record_answer
L ▼
1
0
0
1
R ▼
1
2
0
3
1
4
Window: [1, 0, 1]
Metric: 2
Answer: 6
expand
L ▼
1
0
0
1
1
2
R ▼
0
3
1
4
Window: [1, 0, 1, 0]
Metric: 2
Answer: 10
record_answer
L ▼
1
0
0
1
1
2
R ▼
0
3
1
4
Window: [1, 0, 1, 0]
Metric: 2
Answer: 10
shrink
1
0
L ▼
0
1
1
2
0
3
R ▼
1
4
Window: [0, 1, 0, 1]
Metric: 2
Answer: 14
record_answer
1
0
L ▼
0
1
1
2
0
3
R ▼
1
4
Window: [0, 1, 0, 1]
Metric: 2
Answer: 14
prune
1
0
L ▼
0
1
1
2
0
3
R ▼
1
4
Window: [0, 1, 0, 1]
Metric: 2
Answer: 14
expand
L ▼
1
0
0
1
1
2
0
3
1
4
Metric: 0
Answer: 0
expand
L=R
1
0
0
1
1
2
0
3
1
4
Window: [1]
Metric: 1
Answer: 1
record_answer
L=R
1
0
0
1
1
2
0
3
1
4
Window: [1]
Metric: 1
Answer: 1
expand
L ▼
1
0
R ▼
0
1
1
2
0
3
1
4
Window: [1, 0]
Metric: 1
Answer: 3
record_answer
L ▼
1
0
R ▼
0
1
1
2
0
3
1
4
Window: [1, 0]
Metric: 1
Answer: 3
shrink
1
0
L ▼
0
1
R ▼
1
2
0
3
1
4
Window: [0, 1]
Metric: 1
Answer: 4
record_answer
1
0
L ▼
0
1
R ▼
1
2
0
3
1
4
Window: [0, 1]
Metric: 1
Answer: 6
record_answer
L ▼
1
0
0
1
R ▼
1
2
0
3
1
4
Window: [1, 0, 1]
Metric: 2
Answer: 4
Key Takeaways
✓ The difference of counts of subarrays with sum ≤ goal and sum ≤ goal-1 gives the exact count of subarrays with sum = goal.
This insight is hard to see from code alone because it relies on understanding the counting logic behind the two sliding windows.
✓ Sliding window expansion and contraction maintain a valid sum constraint efficiently without enumerating all subarrays.
Visualizing pointer movements clarifies how the window adjusts dynamically to keep the sum within bounds.
✓ Counting subarrays by adding window size at each step avoids nested loops and reduces complexity.
Seeing the incremental count updates helps understand why the algorithm is efficient.
Practice
(1/5)
1. You are given a string and need to find the length of the longest substring where no character repeats. Which approach guarantees an optimal solution with linear time complexity?
easy
A. Brute force checking all substrings and verifying uniqueness by sorting each substring
B. Sliding window with a hash map tracking the last seen index of each character to dynamically adjust the window
C. Dynamic programming by storing longest substring lengths ending at each index without duplicates
D. Greedy approach by always extending the substring until a duplicate is found, then restarting from next character
Solution
Step 1: Understand problem constraints
The problem requires finding the longest substring without repeating characters, which suggests a variable-size window to track unique characters efficiently.
Step 2: Evaluate approaches
Brute force and greedy approaches either have high time complexity or fail to adjust the window correctly. Dynamic programming is not straightforward here. The sliding window with a hash map efficiently tracks last seen indices and adjusts the window in O(n) time.
Final Answer:
Option B -> Option B
Quick Check:
Sliding window with index tracking is the known optimal pattern [OK]
Hint: Sliding window with index map -> O(n) solution [OK]
Common Mistakes:
Confusing greedy restart with sliding window
Using DP without clear state definition
2. Consider the following Python function implementing the sliding window approach to find the maximum sum subarray of size k. What is the value of window_sum after the second iteration of the for-loop when called with arr = [1, 3, 2, 6] and k = 2?
def max_sum_subarray_sliding_window(arr, k):
n = len(arr)
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, n):
window_sum += arr[i] - arr[i - k]
if window_sum > max_sum:
max_sum = window_sum
return max_sum
Hint: Track window_sum updates carefully per iteration [OK]
Common Mistakes:
Off-by-one errors in loop index
Confusing window_sum with max_sum
Forgetting to subtract the element leaving the window
3. You are given an array of positive integers and a target sum. You need to find the length of the smallest contiguous subarray whose sum is at least the target. Which algorithmic approach guarantees an optimal O(n) time solution for this problem?
easy
A. Brute force nested loops checking all subarrays
B. Sorting the array and using binary search for subarray sums
C. Dynamic programming with memoization over subarray sums
D. Sliding window with two pointers adjusting window size dynamically
Solution
Step 1: Understand problem constraints
The problem requires finding the minimal length subarray with sum ≥ target, which suggests a variable-size window approach.
Step 2: Identify algorithm that adjusts window size efficiently
Sliding window with two pointers can expand and shrink the window in O(n) time, ensuring minimal length is found without checking all subarrays.
Final Answer:
Option D -> Option D
Quick Check:
Sliding window is known for O(n) minimal subarray sum solutions [OK]
Hint: Minimal subarray sum -> variable-size sliding window [OK]
Common Mistakes:
Thinking sorting helps with contiguous subarrays
Assuming DP is needed for minimal length
Using brute force for optimality
4. What is the time complexity of the optimal sliding window with count matching algorithm for finding all anagrams of p in s, where n = len(s) and m = len(p)?
medium
A. O(n), because the window slides once over s and frequency counts are updated in constant time.
B. O(n * m), because each window requires comparing frequency maps of size m.
C. O(n * 26), because frequency arrays of fixed size 26 are compared at each step.
D. O(n log m), due to sorting substrings during comparison.
Solution
Step 1: Identify main loop operations
The window slides over s once, so O(n) iterations.
Step 2: Check frequency updates and comparisons
Frequency counts are arrays of fixed size 26, updated in O(1) time; matches count updated in O(1).
Final Answer:
Option A -> Option A
Quick Check:
Sliding window with count matching is linear time [OK]
Hint: Fixed alphabet size makes frequency updates O(1) [OK]
Common Mistakes:
Assuming frequency map comparison is O(m)
Confusing n*m with n
Thinking sorting is involved
5. The following code attempts to find the length of the longest substring with at most k distinct characters. Identify the bug that causes incorrect results on some inputs.
from collections import OrderedDict
def length_of_longest_substring_k_distinct(s: str, k: int) -> int:
if k == 0 or not s:
return 0
left = 0
max_length = 0
last_seen = OrderedDict()
for right, char in enumerate(s):
if char in last_seen:
del last_seen[char]
last_seen[char] = right
max_length = max(max_length, right - left + 1)
if len(last_seen) > k:
_, idx = last_seen.popitem(last=False)
left = idx + 1
return max_length
medium
A. Not handling the case when k is zero or string is empty
B. Deleting the character from last_seen before re-inserting it
C. Updating max_length before shrinking the window when distinct chars exceed k
D. Using OrderedDict instead of a frequency map
Solution
Step 1: Locate max_length update position
max_length is updated before shrinking the window when distinct chars exceed k, so invalid windows are counted.
Step 2: Understand impact
This causes max_length to include substrings with more than k distinct characters, violating constraints.
Final Answer:
Option C -> Option C
Quick Check:
Moving max_length update after shrinking fixes correctness [OK]
Hint: Update max_length only after ensuring window is valid [OK]
Common Mistakes:
Updating max_length too early before shrinking window
Confusing order of operations in sliding window
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.