FastPrepCount Subarrays with Sum K
Problems/Count Subarrays with Sum K

Count Subarrays with Sum K

Indeed logoIndeed● MediumNEW GRADOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: This is Subarray Sum Equals K, the number of contiguous subarrays of arr that add up to k, asked as the second of three questions in the first online test.

The report gives no limits. Here, arr has 1 to 2 * 10^4 values from -10^4 to 10^4, k is between -2 * 10^8 and 2 * 10^8, and only non-empty subarrays count.

The judged task matches the report at about 90%.

You are given an integer array arr and an integer k.

A subarray is a non-empty run of consecutive elements of arr. Return how many subarrays have elements that add up to exactly k.

Subarrays at different positions count separately, even when they hold the same values.

Function

countSubarrays(arr: int[], k: int) → int

Examples

Example 1

arr = [2,-1,1,2]k = 2return = 4

Four subarrays add up to 2: [2] at the start, [2,-1,1], [-1,1,2], and [2] at the end. The answer is 4.

Example 2

arr = [0,0,0]k = 0return = 6

Every one of the six subarrays sums to 0: three of length 1, two of length 2, and one of length 3. The answer is 6.

Example 3

arr = [4,1,2]k = 6return = 0

The sums are 4, 5, 7 starting at index 0, 1, 3 starting at index 1, and 2 starting at index 2. None is 6, so the answer is 0.

Constraints

  • 1 <= arr.length <= 2 * 10^4
  • -10^4 <= arr[i] <= 10^4
  • -2 * 10^8 <= k <= 2 * 10^8

More Indeed problems

  • Insert into an Unrolled Linked ListPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
  • Course Completion OrderPHONE SCREEN · Seen May 2025
  • Recipes You Can PreparePHONE SCREEN · Seen May 2025
All Indeed interview questionsSee Indeed hiring insights
Saved
class Solution {
    public int countSubarrays(int[] arr, int k) {
        // Write your code here.
    }
}
Checking account…