Longest Subarray with a Target Sum
Updated
Problem statement
You are given an integer array nums and a target. Find the longest nonempty section of consecutive array elements whose sum equals target. Return its length, or 0 if no such section exists.
For this exercise, assume negative and zero values are allowed, and use 64-bit sums.
Function
longestTargetSum(nums: int[], target: long) → intExamples
Example 1
nums = [1,-1,5,-2,3]target = 3return = 4The first four values sum to 3. No length-five subarray qualifies.
Example 2
nums = [2,2]target = 3return = 0No nonempty contiguous subarray has sum 3.
Constraints
- For this exercise, assume
0 <= nums.length <= 10^5. -10^9 <= nums[i] <= 10^9.-10^14 <= target <= 10^14.
More PeopleStrong Onsite Interview questions
- Add Two Binary StringsONSITE INTERVIEW · Seen Mar 2026
- Four SumONSITE INTERVIEW · Seen Mar 2026
- LRU Cache OperationsONSITE INTERVIEW · Seen Mar 2026
- Sliding Window MaximumONSITE INTERVIEW · Seen Mar 2026
- Find the Entry of a Linked List CycleONSITE INTERVIEW · Seen Sep 2025
- Integer to English Words: Up to 20 DigitsONSITE INTERVIEW · Seen Sep 2025
- Word Ladder II: All Shortest TransformationsONSITE INTERVIEW · Seen Sep 2025
- Detect a Cycle in a Linked ListONSITE INTERVIEW · Seen May 2025
- First Nonrepeating CharacterONSITE INTERVIEW · Seen May 2025
- Lowest Common Ancestor in a BSTONSITE INTERVIEW · Seen May 2025
Similar questions at other companies
- Count Subarrays with Equal Even and Odd CountsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Maximum Subarray Sum with Equal EndpointsGoogle · ONSITE INTERVIEWGoogle interview questions
- Count Subarrays with Sum KMakeMyTrip.com · ONSITE INTERVIEWMakeMyTrip.com interview questions
- Subarray Sum Equals KApple · PHONE SCREEN · ONSITE INTERVIEWApple interview questions
- Longest Equal-Zero-One SubarrayMotive · PHONE SCREEN · ONSITE INTERVIEWMotive interview questions
- Find and Measure the Longest Target-Sum SubarrayMeta · ONSITE INTERVIEWMeta interview questions
- Count Subarrays Whose Sum Is KExpedia · ONSITE INTERVIEWExpedia interview questions
- Maximum Sum Desirable SubarrayGroww · PHONE SCREEN
- Maximum Size Subarray Sum Equals KeBay · PHONE SCREENeBay interview questions
- Count Subarrays With Target SumAmazon · PHONE SCREEN