FastPrepFind and Measure the Longest Target-Sum Subarray

Find and Measure the Longest Target-Sum Subarray

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given an integer array nums and a target k, consider every non-empty contiguous subarray whose elements sum to k.

Return [existsFlag, longestLength]. Set existsFlag to 1 if at least one qualifying subarray exists, or 0 otherwise. Set longestLength to the maximum number of elements in any qualifying subarray. If no qualifying subarray exists, return [0, 0].

Values may be positive, negative, or zero. A subsequence that skips elements does not count.

Function

findLongestTargetSubarray(nums: int[], k: int) → int[]

Examples

Example 1

nums = [1,2,3,-2,2]k = 3return = [1,3]

The first three values sum to 6, but [3,-2,2] sums to 3 with length 3; no longer matching subarray exists.

Example 2

nums = [1,-1,1,-1,1]k = 1return = [1,5]

The entire array sums to 1 and is the longest possible qualifying subarray.

Example 3

nums = [2,4,6]k = 5return = [0,0]

No non-empty contiguous subarray sums to 5.

Constraints

  • 1 <= nums.length <= 20000.
  • -1000 <= nums[i] <= 1000.
  • -10000000 <= k <= 10000000.

More Meta problems

See Meta hiring insights
public int[] findLongestTargetSubarray(int[] nums, int k) {
    // Write your code here.
}
nums[1,2,3,-2,2]
k3
expected[1,3]
Checking account…