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

DSA
Medium
Google
70K views

Given an array of non-negative integers, find a contiguous subarray that sums to a target value. This is a classic sliding window problem testing optimization skills.

Why Interviewers Ask This

Interviewers ask this to verify knowledge of the sliding window technique, which is crucial for array problems. They want to ensure the candidate understands why this method works specifically for non-negative numbers due to monotonicity. It also tests the ability to reduce time complexity from O(n^2) to O(n).

How to Answer This Question

Explain the sliding window concept where you maintain a current sum and expand the window by moving the right pointer. If the sum exceeds the target, shrink the window from the left. Since numbers are non-negative, increasing the window size always increases the sum, allowing this greedy shrinking. Walk through an example showing how the window expands and contracts to find the target.

Key Points to Cover

  • Utilize sliding window for O(n) complexity
  • Expand window when sum is too small
  • Shrink window when sum exceeds target
  • Leverage non-negative property for correctness

Sample Answer

I would use a sliding window approach with two pointers, start and end. I expand the window by adding elements from the end until the sum equals or exceeds the target. If the sum exceeds the target, I remove elements from the start until the sum is less than or equal to the target again. Since all numbers are non-negative, this guarantees that if a solution exists, we will find it. This runs in O(n) time with O(1) space.

Common Mistakes to Avoid

  • Trying to use prefix sums unnecessarily
  • Failing to handle the case where no subarray exists
  • Incorrectly updating pointers when sum matches

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