560. Subarray Sum Equals K - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

Given an integer array nums and an integer k, your task is to find the total number of continuous subarrays whose sum equals to k.

A subarray is a contiguous sequence of elements within an array.

Example 1:

  • Input:
    nums = [1, 1, 1], k = 2
    
  • Output:
    2
    
  • Explanation:
    The subarrays that sum up to 2 are [1, 1] starting at index 0 and [1, 1] starting at index 1.

Example 2:

  • Input:
    nums = [1, 2, 3], k = 3
    
  • Output:
    2
    
  • Explanation:
    The subarrays that sum up to 3 are [1, 2] and [3].

Constraints:

  • The length of the array is in the range [1, 20000].
  • The range of numbers in the array is [-1000, 1000].
  • The value of k is in the range [-10^7, 10^7].

Hints Before Diving into the Solution

  1. Brute Force Idea:
    Think about checking all possible subarrays and summing their elements. How many subarrays are there? Can you optimize it?

  2. Prefix Sum and HashMap:
    Consider using prefix sums. If you know the sum of all elements up to two different indices, you can compute the sum of the subarray between them in constant time.
    Use a hash map to store the frequencies of prefix sums encountered so far. This will help you quickly determine how many previous subarrays can form a valid subarray ending at the current index.

Approach 1: Brute Force (Not Optimal)

Explanation:

  • Idea:
    Check every possible subarray by using two nested loops.
    For each subarray, calculate its sum and check if it equals k.

  • Steps:

    1. Iterate over all starting indices.
    2. For each starting index, iterate over all ending indices.
    3. Sum up the elements of the subarray and check if the sum equals k.
  • Drawback:
    Time complexity is O(n²) or worse. This approach will not scale well with larger inputs.

Approach 2: Optimal Solution Using Prefix Sum and Hash Map

Overview:

  • Prefix Sum Concept:
    A prefix sum at index i is the sum of all elements from the beginning of the array up to i. Denote this as prefixSum[i].

  • Key Observation:
    If you have two indices i and j (with i < j) such that:

    prefixSum[j] - prefixSum[i] = k
    

    then the subarray from index i + 1 to j sums to k.

  • Using a Hash Map:
    Use a hash map (sumCount) to keep track of how many times a particular prefix sum occurs as you iterate through the array.
    For each new prefix sum, check if currentPrefixSum - k exists in the map. If it does, then there are that many subarrays ending at the current index whose sum is k.

Detailed Walkthrough:

  1. Initialization:

    • Set currentPrefixSum = 0.
    • Use a hash map sumCount to store frequency of prefix sums. Initialize it with {0: 1} to account for subarrays that start from index 0.
    • Initialize a counter totalCount to 0.
  2. Iteration:

    • For each number in the array:
      • Update the currentPrefixSum by adding the current number.
      • Check if currentPrefixSum - k exists in sumCount. If yes, add its frequency to totalCount because each occurrence represents a valid subarray ending at the current index.
      • Update the hash map with the current prefix sum.
  3. Return:
    After processing all elements, totalCount holds the total number of subarrays with sum equal to k.

Complexity Analysis

  • Time Complexity:
    O(n), since we traverse the array once, and each hash map operation is O(1) on average.

  • Space Complexity:
    O(n), for storing the prefix sums in the hash map in the worst case.

Code Implementations

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Common Pitfalls and Edge Cases

Common Mistakes:

  • Not Initializing the HashMap with {0: 1}:
    This initialization is critical for subarrays that start at index 0.

  • Ignoring Negative Numbers:
    Since nums may contain negative numbers, ensure that the algorithm correctly handles decreasing prefix sums.

  • Double Counting:
    Care must be taken to update the hash map after checking for the required prefix difference to avoid double counting.

Edge Cases:

  • Empty Array:
    Return 0 since there are no subarrays.

  • No Valid Subarray:
    If no subarray sums to k, the algorithm should return 0.

  • All Elements Equal Zero:
    Special care is needed when the array contains all zeros, as there could be many valid subarrays.

  • Longest Subarray with Sum Equals k
  • Subarray Product Less Than K
  • Find Sum of Subarray Minimums
TAGS
LeetCode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Does OpenAI use C++?
How many tools are in AWS?
How well does Twitter pay?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;