Bird
Raised Fist0
Interview Prepsliding-windowmediumAmazonGoogleFacebook

Minimum Size Subarray Sum

Choose your preparation mode4 modes available
</>
IDE
def min_subarray_len(target: int, nums: list[int]) -> int:public int minSubArrayLen(int target, int[] nums)int minSubArrayLen(int target, vector<int>& nums)function minSubArrayLen(target, nums)
def min_subarray_len(target, nums):
    # Write your solution here
    pass
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int minSubArrayLen(int target, vector<int>& nums) {
    // Write your solution here
    return 0;
}
function minSubArrayLen(target, nums) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 1Greedy approach returns first element >= target without checking minimal length subarray.✅ Implement sliding window that shrinks from left when sum >= target to find minimal length.
Wrong: 0Code returns 0 incorrectly when single element equals or exceeds target.✅ Add base case to check if any single element >= target and return 1 immediately.
Wrong: 4Off-by-one error in length calculation returns incorrect minimal length.✅ Calculate length as (right - left + 1) when updating minimal length.
Wrong: non-zeroCode does not handle case where sum of all elements is less than target, returning non-zero instead of 0.✅ Check total sum before sliding window; return 0 if sum < target.
Wrong: TLEUsing brute force nested loops leads to time limit exceeded on large inputs.✅ Use O(n) sliding window approach instead of O(n^2) brute force.
✓
Test Cases
t1_01basic
Input{"target":7,"nums":[2,3,1,2,4,3]}
Expected2

The subarray [4,3] has the minimal length 2 with sum >= 7.

t1_02basic
Input{"target":15,"nums":[1,2,3,4,5]}
Expected5

Only the entire array sums to 15, so minimal length is 5.

t2_01edge
Input{"target":10,"nums":[1,1,1,1,1]}
Expected0

Sum of all elements is 5, less than target 10, so no valid subarray exists.

t2_02edge
Input{"target":4,"nums":[4]}
Expected1

Single element equals target, minimal subarray length is 1.

t2_03edge
Input{"target":10,"nums":[2,2,2,2,2]}
Expected5

Sum of all elements is exactly 10; minimal subarray is entire array length 5.

t2_04edge
Input{"target":1,"nums":[1]}
Expected1

Minimal input size with one element equal to target returns 1.

t3_01corner
Input{"target":8,"nums":[1,4,4]}
Expected2

Subarray [4,4] sums to 8 with minimal length 2; greedy picking first 4 only fails.

t3_02corner
Input{"target":5,"nums":[5,1,1,1,1]}
Expected1

Single element 5 meets target; minimal length is 1, not sum of multiple elements.

t3_03corner
Input{"target":11,"nums":[1,2,3,4,5]}
Expected3

Subarray [3,4,5] sums to 12 >= 11 with minimal length 3; off-by-one errors cause wrong length.

t4_01performance
Input{"target":500000,"nums":[10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000]}
⏱ Performance - must finish in 2000ms

n=100, O(n) sliding window must complete within 2s; brute force O(n^2) will TLE.

Practice

(1/5)
1. Consider the following Python code implementing the optimal sliding window approach for the character replacement problem. What is the returned value when the input is s = "AABA" and k = 1?
easy
A. 4
B. 3
C. 2
D. 1

Solution

  1. Step 1: Trace window expansion and frequency updates

    Index 0: freq[A]=1, max_count=1, window=[0,0], max_len=1 Index 1: freq[A]=2, max_count=2, window=[0,1], max_len=2 Index 2: freq[B]=1, max_count=2, window=[0,2], window size=3, replacements needed=1 ≤ k=1, max_len=3 Index 3: freq[A]=3, max_count=3, window=[0,3], window size=4, replacements needed=1 ≤ k=1, max_len=4
  2. Step 2: Check while condition and final max_len

    At index 3, window size 4 with max_count 3 means 1 replacement needed, which is allowed. So max_len updates to 4. The function returns 4.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Window expands fully with one replacement allowed [OK]
Hint: Max length includes full string if replacements ≤ k [OK]
Common Mistakes:
  • Off-by-one error in window size calculation
  • Not updating max_count correctly
  • Misunderstanding when to shrink window
2. Consider the following buggy code for maxSatisfied. Which line contains the subtle bug that causes incorrect results on some inputs?
def maxSatisfied(customers, grumpy, X):
    n = len(customers)
    base_satisfied = 0
    for i in range(n):
        if grumpy[i] == 0:
            base_satisfied += customers[i]
    window_sum = 0
    for i in range(X):
        if grumpy[i] == 1:
            window_sum += customers[i]
    max_extra = window_sum
    for i in range(X, n):
        if grumpy[i] == 1:
            window_sum += customers[i]
        if grumpy[i - X] == 0:
            window_sum -= customers[i - X]
        if window_sum > max_extra:
            max_extra = window_sum
    return base_satisfied + max_extra
medium
A. Line checking if grumpy[i] == 1 before adding customers[i]
B. Line initializing base_satisfied with customers where grumpy[i] == 0
C. Line checking if grumpy[i - X] == 0 before subtracting customers[i - X]
D. Line updating max_extra when window_sum > max_extra

Solution

  1. Step 1: Identify subtraction condition

    The code subtracts customers[i - X] only if grumpy[i - X] == 0, but it should subtract only if grumpy[i - X] == 1 because only grumpy customers were added.
  2. Step 2: Consequence of bug

    This causes incorrect window sums, as some grumpy customers are never subtracted, inflating window_sum.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Subtraction condition must match addition condition [OK]
Hint: Check symmetry of add and subtract conditions [OK]
Common Mistakes:
  • Confusing grumpy check in subtraction
  • Forgetting to subtract outgoing element
  • Mixing base satisfaction with window sums
3. The following code attempts to solve the Longest Repeating Character Replacement problem. Which line contains a subtle bug that can cause incorrect results on some inputs?
medium
A. Line incrementing left pointer inside the while loop
B. Line incrementing freq for s[right]
C. Line updating max_count inside the while loop after shrinking the window
D. Line updating max_len after the while loop

Solution

  1. Step 1: Understand max_count usage

    max_count should track the max frequency character in the current window efficiently without recomputing entire freq array.
  2. Step 2: Identify bug in max_count update

    Updating max_count by max(freq) inside the while loop is costly and can cause stale or incorrect max_count, leading to wrong window shrinking decisions.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    max_count must not be recomputed inside the shrinking loop [OK]
Hint: max_count updated only on window expansion, not shrinking [OK]
Common Mistakes:
  • Recomputing max_count on every shrink
  • Not updating frequency counts correctly
  • Shrinking window too early or late
4. What is the time complexity of the optimal sliding window solution that uses a queue to track zero positions for the Max Consecutive Ones III problem, given an input array of length n and integer k?
medium
A. O(n * k) because each zero can cause multiple window shifts
B. O(n) because each element is visited at most twice by the two pointers
C. O(n^2) because the queue operations inside the loop cause nested behavior
D. O(k) because the queue size is limited to k zeros only

Solution

  1. Step 1: Identify loop behavior

    The right pointer iterates over all n elements once, and the left pointer only moves forward when zeros exceed k.
  2. Step 2: Analyze queue operations and pointer moves

    Each zero index is enqueued once and dequeued once, so total operations are O(n). However, each zero can cause the left pointer to move multiple times in worst case, leading to O(n * k) complexity.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    While the queue operations are O(n), the window shifts can multiply by k in worst cases [OK]
Hint: Consider worst-case window shifts caused by zeros [OK]
Common Mistakes:
  • Assuming strictly linear without considering multiple shifts
  • Confusing queue size with total operations
  • Ignoring worst-case scenarios
5. Suppose the problem is modified so that characters can be reused multiple times but you want the longest substring where each character appears at most twice. Which modification to the sliding window approach is correct?
hard
A. Use a hash set to track unique characters and reset the window whenever a duplicate is found
B. Use a dynamic programming approach storing max length substrings ending at each index
C. Use a brute force approach checking all substrings since sliding window cannot handle counts >1
D. Use a hash map to count occurrences of each character and shrink the window when any count exceeds 2

Solution

  1. Step 1: Understand the new constraint

    Characters can appear at most twice, so we must track counts, not just presence.
  2. Step 2: Modify sliding window

    Use a hash map to count occurrences. Expand right pointer, increment counts. When any count > 2, move left pointer and decrement counts until valid.
  3. Step 3: Evaluate other options

    Hash set only tracks presence (not counts), brute force is inefficient, DP is not straightforward here.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Counting occurrences with sliding window handles "at most twice" constraint [OK]
Hint: Track counts, not just presence, for repeated allowed chars [OK]
Common Mistakes:
  • Using hash set instead of counts
  • Assuming sliding window can't handle counts >1
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard