Bird
Raised Fist0
Interview Prepsliding-windoweasyAmazonGoogle

Maximum Sum Subarray of Size K

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

int maxSumSubarray(vector<int> &arr, int k) {
    // Write your solution here
    return 0;
}
function maxSumSubarray(arr, k) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 0Initializing max sum to 0 and failing on all negative arrays.✅ Initialize max sum to first window sum or -inf to handle negative sums.
Wrong: Incorrect sum from non-contiguous elementsUsing a greedy approach picking largest elements ignoring contiguity.✅ Use sliding window to consider only contiguous subarrays of size K.
Wrong: Runtime error or crashNot handling empty array or K=0 input properly.✅ Add base case checks: if array empty or K=0, return 0.
Wrong: TimeoutUsing brute force O(n*k) approach on large inputs.✅ Implement O(n) sliding window algorithm.
✓
Test Cases
t1_01basic
Input{"arr":[2,1,5,1,3,2],"k":3}
Expected9

The subarray [5, 1, 3] has the maximum sum 9.

t1_02basic
Input{"arr":[4,2,1,7,8,1,2,8,1,0],"k":4}
Expected19

The subarray [7, 8, 1, 8] has the maximum sum 24.

t2_01edge
Input{"arr":[],"k":0}
Expected0

Empty array and K=0 means no subarray; max sum is 0 by definition.

t2_02edge
Input{"arr":[5],"k":1}
Expected5

Single element array with K=1; max sum is the element itself.

t2_03edge
Input{"arr":[3,-1,-2,-4,-5],"k":3}
Expected0

All negative numbers; max sum subarray of size 3 is [-1, -2, -4] with sum -7.

t2_04edge
Input{"arr":[0,0,0,0],"k":2}
Expected0

Array contains zeros; max sum subarray of size 2 is 0.

t3_01corner
Input{"arr":[1,2,3,4,5],"k":5}
Expected15

K equals array length; max sum is sum of entire array.

t3_02corner
Input{"arr":[0,0,0,0,0],"k":3}
Expected0

Array with zeros; max sum subarray of size 3 is 0.

t3_03corner
Input{"arr":[1,3,2,1,4,1,5],"k":2}
Expected6

Greedy trap test: max sum subarray of size 2 is [5,1] with sum 6, not just picking largest elements non-contiguously.

t4_01performance
Input{"arr":[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],"k":50}
⏱ Performance - must finish in 2000ms

Large input with n=100 and k=50; O(n*k) brute force will time out, O(n) sliding window must complete within 2s.

Practice

(1/5)
1. Given the following code snippet, what is the output when calling numSubarraysWithSum([1,0,1], 2)?
easy
A. 2
B. 4
C. 1
D. 3

Solution

  1. Step 1: Trace atMost(2)

    Right=0: current_sum=1 ≤2, count=1; Right=1: current_sum=1 ≤2, count=1+2=3; Right=2: current_sum=2 ≤2, count=3+3=6
  2. Step 2: Trace atMost(1)

    Right=0: current_sum=1 ≤1, count=1; Right=1: current_sum=1 ≤1, count=1+2=3; Right=2: current_sum=2 >1, shrink window: current_sum=1, left=1, count=3+2=5
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    numSubarraysWithSum = 6 - 5 = 1 [BUG]
Hint: Subtract atMost(goal-1) from atMost(goal) to get exact count [OK]
Common Mistakes:
  • Miscounting subarrays when shrinking window
  • Off-by-one errors in count increments
  • Confusing atMost(goal) with exact count
2. What is the time complexity of the optimal sliding window solution for the Longest Repeating Character Replacement problem, assuming the input string length is n and the character set size is fixed (e.g., 26 uppercase letters)?
medium
A. O(n) because each character is visited at most twice by left and right pointers
B. O(n^2) because the window can shrink and expand multiple times
C. O(n * k) because the inner loop depends on the number of allowed replacements
D. O(n) but with O(n) auxiliary space due to frequency map storage

Solution

  1. Step 1: Analyze pointer movements

    Right pointer moves from 0 to n-1 once. Left pointer only moves forward when window is invalid, also at most n times.
  2. Step 2: Consider frequency array and fixed character set

    Frequency array is fixed size (26), so updates are O(1). No nested loops over n inside main loop.
  3. Step 3: Analyze space complexity

    The frequency array uses O(1) space since the character set is fixed, not O(n).
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Two-pointer linear scan with fixed-size frequency array [OK]
Hint: Two pointers each move forward at most n times [OK]
Common Mistakes:
  • Assuming nested loops cause O(n^2)
  • Thinking k affects inner loop complexity
  • Confusing frequency map space with time complexity
3. What is the time complexity of the sliding window solution for finding the maximum average subarray of size k in an array of length n, and why might some candidates mistakenly think it is higher?
medium
A. O(n) because each element is added and removed exactly once from the window sum
B. O(n*k) because each window sum is recomputed from scratch
C. O(n log k) due to sorting elements within each window
D. O(k) because the window size dominates the computation

Solution

  1. Step 1: Analyze loop operations

    The sliding window sums are updated by adding one new element and removing one old element per iteration, so each element is processed twice.
  2. Step 2: Identify complexity

    Since the loop runs n-k times and each iteration is O(1), total time is O(n). The common mistake is thinking sum is recomputed fully each time, which is O(n*k).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sliding window updates sum in constant time per iteration [OK]
Hint: Sliding window updates sum in O(1) per iteration [OK]
Common Mistakes:
  • Assuming sum recomputed fully each window
  • Confusing window size k with input size n
4. The following code attempts to implement the optimal sliding window approach to check if s2 contains a permutation of s1. Identify the line containing the subtle bug that can cause incorrect results.
medium
A. Line checking if window_count[idx] == count[idx] to increment formed
B. Line computing required as sum of positive counts
C. Line decrementing window_count[left_idx] before adjusting formed
D. Line checking if len_s1 > len_s2 at start

Solution

  1. Step 1: Identify bug in window shrinking logic

    The code decrements window_count[left_idx] before checking if it equals count[left_idx]. This causes incorrect formed count updates because the check should happen before decrement.
  2. Step 2: Correct order of operations

    To fix, check if window_count[left_idx] == count[left_idx] before decrementing window_count[left_idx], then decrement and adjust formed accordingly.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Formed count must reflect window state before decrement [OK]
Hint: Check order of decrement and formed adjustment in window shrink [OK]
Common Mistakes:
  • Adjusting formed after decrementing counts
  • Miscounting required matches
5. Suppose the problem is modified so that characters in p can be reused multiple times when matching substrings in s (i.e., find substrings in s that can be formed by repeating characters from p any number of times). Which of the following algorithmic changes correctly adapts the sliding window approach?
hard
A. Keep the fixed window size equal to len(p) and use the same frequency matching logic.
B. Sort p and each window substring, then compare sorted strings for equality.
C. Use a variable-size sliding window and check if the window's frequency counts are all less than or equal to p's counts multiplied by the number of repeats.
D. Use a variable-size sliding window and check if all characters in the window appear in p, ignoring counts.

Solution

  1. Step 1: Understand reuse of characters

    Characters in p can be repeated multiple times, so window size is variable and frequency counts can exceed original counts.
  2. Step 2: Adapt sliding window logic

    Use variable-size window and verify window counts do not exceed allowed multiples of p's counts.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Variable window and count comparison with multiples handles reuse correctly [OK]
Hint: Variable window size with count limits handles reuse [OK]
Common Mistakes:
  • Keeping fixed window size
  • Ignoring counts and only checking character presence
  • Sorting substrings repeatedly
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