Longest Subarray With Sum K

Coding · Medium · Free problem
Given an array $A_1, A_2, \ldots, A_n$ of integers (which may be negative) and a target value $K$, find the length of the longest contiguous subarray whose elements sum to exactly $K$. **Constraints:** -
\leq n \leq 10^5$ - $-10^9 \leq A_i \leq 10^9$ - $-10^{18} \leq K \leq 10^{18}$ **Example 1:** Input: $A = [1, -1, 5, -2, 3]$, $K = 3$ Output: $4$ Explanation: The subarray $[1, -1, 5, -2]$ sums to $3$ and has length $4$. **Example 2:** Input: $A = [-2, -1, 2, 1]$, $K = 1$ Output:
$ Explanation: The subarray $[-1, 2]$ sums to
$ and has length
$. Design an algorithm that runs in $O(n)$ time and $O(n)$ space. Discuss overflow safeguards when element values can be large.

Open the full interactive solver, hints, and worked solution →