Longest subarray with sum K

Hashing FAQs Hard
  • This problem is based on the concept of "Sliding Window Algorithm" which is very popular in dealing with array or list data structures in actual software development
  • Most commonly, this algorithm is used in networking protocols such as TCP to avoid network congestion by controlling the amount of data sent without receiving an acknowledgment, and in multimedia and graphics, where it improves user experience by ensuring smooth data flow and rendering

Given an array nums of size n and an integer k, find the length of the longest sub-array that sums up to k. If no such sub-array exists, return 0.

Examples:

Input: nums = [10, 5, 2, 7, 1, 9],  k=15

Output: 4

Explanation: The longest sub-array with a sum equal to 15 is [5, 2, 7, 1], which has a length of 4. This sub-array starts at index 1 and ends at index 4, and the sum of its elements (5 + 2 + 7 + 1) equals 15. Therefore, the length of this sub-array is 4.

Input: nums = [-3, 2, 1], k=6

Output: 0

Explanation: There is no sub-array in the array that sums to 6. Therefore, the output is 0.

Input: nums = [-1, 1, 1], k=1

Constraints

  •  1<=n<=105
  •  -105<=nums[i]<=105
  •  -109<= k<=109

Hints

  • Use a hash map to store the prefix sum of the array at each index. This helps efficiently track subarrays that sum to k.
  • For each index i, calculate the prefix sum up to that point. If the prefix sum minus k exists in the hash map, the subarray between those indices sums to k.

Company Tags

Zynga Nutanix Intel Oracle Johnson & Johnson Flipkart Docker Bloomberg GE Healthcare eBay PayPal American Express NVIDIA Robinhood Boston Consulting Group Goldman Sachs Philips Healthcare Medtronic Swiggy HashiCorp Airbnb PwC Deloitte Etsy Cerner Google Microsoft Amazon Meta Apple Netflix Adobe