InferenceAI

Enter at least two characters to search.

Start free

Longest Subarray Summing to K

mediumArrays & Hashing25 min25 XP

Return the length of the longest contiguous subarray of nums (values may be negative) whose sum equals k, or 0 if none exists.

Requirements

  • O(n)O(n) with prefix sums: a subarray (i,j](i, j] sums to kk when Pj−Pi=kP_j - P_i = k.

Examples

EXAMPLE WALKTHROUGHfour long

A guided view of the published example, not a trace of your code.

INPUT[[1,-1,5,-2,3],3]
TASKlongest_sum_k_subarray()
EXPECTED OUTPUT4

Start with the input values shown in this example.

Example 1 of 3

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

Output: 4

Explanation: four long

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

Output: 2

Explanation: two long

Input: nums = [1,2,3], k = 7

Output: 0

Explanation: none

Hint 1

Store the first index at which each prefix sum appears.

Topics

DSAArrays & HashingPython