FastPrepCount Subarrays That Add Up to k
Problems/Count Subarrays That Add Up to k

Count Subarrays That Add Up to k

Adobe logoAdobe● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: This problem counts the contiguous runs of an integer array, negatives allowed, whose values total exactly k. An Adobe SDE2 entry on Taro (a Glassdoor copy) names it as the first of two coding questions in its first technical round, after C++ concept questions; the name is all it gives.

Our choices: negative values and zeros allowed, at most 3000 numbers from -1000 to 1000, k from -3 million to 3 million, and new examples.

The judged task matches the report at about 90%.

Given an integer array nums (values may be negative or zero) and an integer k, count the subarrays whose values add up to exactly k.

A subarray is a non-empty run of neighbouring elements. Two subarrays count separately when they start or end at different positions, even if they hold the same values.

Function

countSubarraysWithSum(nums: int[], k: int) → int

Examples

Example 1

nums = [2,-1,3,-2,1]k = 2return = 4

Four subarrays add up to 2: [2], [-1, 3], [2, -1, 3, -2] and [3, -2, 1].

Example 2

nums = [0,0,5]k = 0return = 3

The subarrays [0] (first), [0] (second) and [0, 0] add up to 0. Each counts separately because it covers different positions.

Example 3

nums = [4,4]k = 5return = 0

The possible sums are 4, 4 and 8. None of them is 5, so the answer is 0.

Constraints

  • 1 <= nums.length <= 3000
  • -1000 <= nums[i] <= 1000
  • -3 * 10^6 <= k <= 3 * 10^6

More Adobe problems

  • Evaluate a Parenthesized Integer ExpressionPHONE SCREEN · Seen Oct 2026
  • All Elements of Two BSTs in OrderPHONE SCREEN · Seen Aug 2026
  • Rotate an Array In PlaceOA · PHONE SCREEN · Seen Aug 2026
All Adobe interview questionsSee Adobe hiring insights
Saved
public int countSubarraysWithSum(int[] nums, int k) {
    // Write your code here.
}
Checking account…