TikTok Coding Interview / OA: Continuous Subarray Sum Equals K

18 Views
No Comments

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, res = true[1,2,3]
  • nums = [1,2,3,4], k = 8, res = false[1,3,4]

This problem is a classic sliding window check on an array of positive integers. Expand the window by adding each number, and shrink it from the left while the sum is greater than k. If the running sum ever equals k, return true; otherwise return false after the scan. Because all numbers are positive, the window sum changes monotonically, which makes the O(n) two-pointer approach work efficiently.

END
 0