VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 02: Hashing

Lesson 2.9 of 12 in this module Unrolled Pro

Longest Subarray with Sum K

The longest contiguous subarray summing to k: from O(n²) running sums, to two pointers when no value is negative, to prefix sums with a first-occurrence map when negatives appear. Why you must never overwrite the first index, and the shortest and balanced-window variants.

about 10 min 7 Python examples 2 quick checks

Problem. Given nums and k, return the length of the longest contiguous subarray whose sum is exactly k (0 if none).

text
nums = [1, 2, 1, 1, 1], k = 3          →   3     ([1, 1, 1])
nums = [1, -1, 5, -2, 3], k = 3        →   4     ([1, -1, 5, -2])
nums = [-2, -1, 2, 1], k = 1           →   2     ([-1, 2])

ML context. "The longest stretch that nets to a target" is the longest balanced window when labels are coded as ±1 (k = 0): the longest period with as many positive as negative predictions, or as many clicks as non-clicks. It also answers "the longest window of a budget log that spends exactly B".

This is lesson 2.8 with a different question (longest, not count), and that changes what the hash map stores.


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Longest Subarray with Sum K"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee