How do you find a subarray with a specific sum efficiently?

DSA
Medium
Google
129.2K views

Given an array of non-negative numbers, the goal is to find a contiguous subarray that sums to a target value. This tests sliding window and prefix sum techniques.

Why Interviewers Ask This

Interviewers ask this to gauge familiarity with the sliding window pattern, which is crucial for subarray problems. They also want to see if the candidate understands why the non-negative constraint allows for an O(n) solution compared to O(n^2) or O(n log n) general cases.

How to Answer This Question

Explain the sliding window approach where you expand the window by adding elements and shrink it when the sum exceeds the target. Since numbers are non-negative, shrinking the window always reduces the sum. Mention edge cases like single element matches or no solution existing.

Key Points to Cover

  • Utilize the non-negative property for sliding window
  • Expand window to increase sum, shrink to decrease
  • Track current sum dynamically
  • Return indices upon finding the target sum

Sample Answer

Since the numbers are non-negative, I can use a sliding window. I maintain a current sum and two pointers, start and end. I expand the window by moving end forward and adding elements to the sum. If the sum equals the target, I return the indices. If the sum exceeds the target, I move start forward and subtract elements until the sum is less than or equal to the target. This runs in linear time O(n).

Common Mistakes to Avoid

  • Applying prefix sum unnecessarily when sliding window works
  • Failing to handle the case where sum exceeds target
  • Not resetting pointers correctly after finding a solution

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 49 DSA questionsBrowse all 121 Google questions