U

45. Longest Subarray with Sum K (Non-negative Numbers)

Med.

Problem Description

Given an array of NN non-negative integers and a target KK, find the length of the longest contiguous subarray whose sum equals KK. If no such subarray exists, print 0.

Input Format

  • •Line 1: Two space-separated integers NN and KK (1≤N≤1051 \le N \le 10^5, 0≤K≤1090 \le K \le 10^9).
  • •Line 2: NN space-separated non-negative integers A1,…,ANA_1, \dots, A_N.

Output Format

Print the length of the longest contiguous subarray whose sum is KK.

Example 1:
Input:
5 5
1 2 3 1 1
Output:
3
Explanation: Subarray [3, 1, 1] has sum 5 and length 3.
Example 2:
Input:
3 10
1 2 3
Output:
0
Explanation: Total array sum is 6 < 10; output 0.
Example 3:
Input:
4 0
0 0 0 0
Output:
4
Explanation: Entire array of zeros has sum 0 and length 4.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online