12. Subarray Sum Equals K

12. Subarray Sum Equals K

Medium
44.0%
1.5k
arrayhash-table
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend or data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A streaming or marketplace platform monitors daily changes in a business metric such as:

  • daily active user change (+ / -)
  • revenue delta (+ / -)
  • latency improvement or regression (+ / -)
  • user sentiment score changes (+ / -)

These daily deltas are stored in an integer array nums.
For an internal analytics report, the company wants to count how many contiguous time windows (continuous ranges of days) have a total change exactly equal to a target value k.

This is a common practice coding problem for DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given an integer array nums and an integer k, return the total number of contiguous subarrays whose sum equals k.

A subarray must be contiguous, meaning it uses consecutive elements from the original array.

Input Format

  • nums: an array of integers (can contain positive, negative, and zero values)
  • k: an integer target sum

Output Format

  • A single integer representing the number of subarrays whose sum equals k

Examples

Example 1:

Input: nums = [1, 1, 1] k = 2
Output: 2
Explanation: [1, 1] from index 1 to 2

Example 2:

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

Constraints

  • 1 <= nums.length <= 100,000
  • -1,000 <= nums[i] <= 1,000
  • -10^7 <= k <= 10^7

Loading editor...

[1,1,1], 2
2

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback