Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Subarray Sum Equals K

LeetCode #560Medium
Running prefix + a count hashmap

Given an integer array and an integer k, return the total number of contiguous subarrays whose elements sum to exactly k.

Asked atAmazonMetaGoogle
step 1 / 58
3
4
7
2
-3
1
4
2
[0][1][2][3][4][5][6][7]
Brute force · every subarray
1given arr, k
2count = 0
3for start in 0..n−1:
4 sum = 0
5 for end in start..n−1:
6 sum += arr[end]
7 if sum == k: count++
8return count
state
  • k7
  • count0

line 1Count the contiguous subarrays whose elements sum to exactly k = 7. Brute force: fix a start, extend the end, keep a running sum, and tally every time it hits 7.