Quant Memo
Coding/●●●●●

Longest subarray that sums to k

Given an integer array nums (values may be negative) and a target k, return the length of the longest contiguous subarray whose sum is exactly k. Return 0 if none exists.

nums = [1, -1, 5, -2, 3], k = 3
-> 4          # [1, -1, 5, -2]

Target O(n)O(n) time.

Show a hint

A subarray (j, i] sums to k when P[j] = P[i] - k. To make that subarray as long as possible, which occurrence of the matching prefix sum do you want?

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions