FastPrepDetect a Contiguous Subarray with Target Sum

Detect a Contiguous Subarray with Target Sum

Meta logoMeta● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given an integer array nums and an integer target.

Return true if at least one nonempty contiguous subarray has a sum equal to target. Otherwise, return false.

The array may contain positive, negative, and zero values.

Function

hasTargetSumSubarray(nums: int[], target: int) → boolean

Examples

Example 1

nums = [1,2,3,4]target = 5return = true

The contiguous subarray [2,3] sums to 5.

Example 2

nums = [4,-2,-1,3]target = 0return = true

The contiguous subarray [-2,-1,3] has sum 0.

Example 3

nums = [2,4,6]target = 5return = false

No nonempty contiguous subarray sums to 5.

Constraints

  • 0 <= nums.length <= 200000.
  • -10^9 <= nums[i] <= 10^9.
  • -10^9 <= target <= 10^9.
  • A qualifying subarray must contain at least one element.
  • The mathematical subarray sum may exceed a signed 32-bit integer.

More Meta problems

See Meta hiring insights
public boolean hasTargetSumSubarray(int[] nums, int target) {
  // write your code here
}
nums[1,2,3,4]
target5
expectedtrue
Checking account…