Subarray Sum Equals K
Problem Statement
You are given an integer array nums and an integer k. The numbers can be negative.
Count how many contiguous, non-empty subarrays add up to exactly k.
An integer array nums and an integer k.
The number of non-empty subarrays whose sum equals k.
[1, 1] at indices 0..1 and [1, 1] at indices 1..2.
[1, 2] (0..1) and [3] (index 2).
- • 1 ≤ nums.length ≤ 2 · 10^4
- • −1000 ≤ nums[i] ≤ 1000
- • −10^7 ≤ k ≤ 10^7
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Try every (start, end) pair and add the block from scratch
Precompute prefix sums; each block sum is one subtraction
count += seen[prefix − k], then seen[prefix]++
Try every start and every end, add up nums[start..end] with a third loop, and count the pairs whose sum is k.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Prefix Sum translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.