WorkspaceProblem lab
ALGORITHM VISUALIZER

Subarray Sum Equals K

Opening the interactive workspace…

Understanding Subarray Sum Equals K

Count contiguous nonempty subarrays whose sum is exactly k.

How it works

A previous prefix equal to currentPrefix minus k starts a subarray with sum k.

Seed the empty prefix with frequency one. Add each value and count prior prefixes equal to sum minus k. Record the current prefix only after counting its matches.

Try an example

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

Output: 2

A previous prefix equal to currentPrefix minus k starts a subarray with sum k.

Constraints

  • 0–64 integers between -1,000,000 and 1,000,000.
  • k is an integer between -64,000,000 and 64,000,000; negative values and zero are allowed.

Use the simulator

Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.

Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.

Related concepts and complexity