How do you find a subarray with a given sum in non-negative numbers?

DSA
Medium
Google
58.2K views

This classic problem asks for a contiguous subarray whose elements sum up to a specific target value. It is a fundamental sliding window application.

Why Interviewers Ask This

Interviewers ask this to test knowledge of the sliding window technique, which is highly relevant for array and stream processing problems. Since the numbers are non-negative, the sum increases monotonically, allowing for an efficient single-pass solution. It demonstrates a candidate's ability to optimize space and time complexity by avoiding unnecessary iterations.

How to Answer This Question

Describe the sliding window approach where you expand the window by adding elements from the right until the sum matches or exceeds the target. If the sum exceeds the target, shrink the window from the left. Explain that this works because non-negative numbers ensure the sum never decreases when expanding. Mention that if no such subarray exists, return an appropriate indicator. Analyze the O(n) time complexity.

Key Points to Cover

  • Applying the sliding window technique effectively
  • Leveraging non-negative property for monotonicity
  • Managing start and end pointers dynamically
  • Achieving linear time complexity

Sample Answer

Since the array contains non-negative numbers, I can use the sliding window technique. I maintain two pointers, 'start' and 'end', and a current sum variable. I increment 'end' and add the element to the current sum. While the current sum is greater than the target, I subtract the element at 'start' and increment 'start'. If the current sum equals the target, I return the indices. This approach ensures that each element is added and removed at most once, resulting in an O(n) time complexity and O(1) space complexity.

Common Mistakes to Avoid

  • Attempting a brute force O(n^2) solution unnecessarily
  • Failing to handle the case where the sum becomes larger than target
  • Not resetting the window correctly when shrinking
  • Ignoring the constraint of non-negative numbers

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 35 DSA questionsBrowse all 109 Google questions