Given an array of positive integers nums and an integer k,
return true if nums has a continuous subarray whose sum equals k.
Examples:
nums = [1,2,3,4], k = 6 → true
(subarray[1,2,3])nums = [1,2,3,4], k = 8 → false
(no continuous subarray sums to 8)nums = [1], k = 6 → false
Since all numbers are positive, we can use a sliding window:
- Expand the right pointer and accumulate the running sum.
- If the sum exceeds
k, shrink the left pointer. - If it matches
k, return true. - If the loop ends without finding a match, return false.
This works in O(n) because the two pointers only move forward.
The VOprep team has long accompanied candidates through various major company OAs and VOs, including Tiktok, Google, Amazon, Citadel, SIG, providing real-time voice assistance, remote practice, and interview pacing reminders to help you stay smooth during critical moments. If you are preparing for Tiktok or similar engineering-focused companies, you can check out our customized support plans—from coding interviews to system design, we offer full guidance to help you succeed.