Binary TreesBinary Trees36
  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Inorder Traversal of a Binary Tree using Recursion
  4. 4Inorder Traversal of a Binary Tree using Iteration
  5. 5Postorder Traversal of a Binary Tree Using Recursion
  6. 6Postorder Traversal of a Binary Tree using Iteration
  7. 7Level Order Traversal of a Binary Tree using Recursion
  8. 8Level Order Traversal of a Binary Tree using Iteration
  9. 9Reverse Level Order Traversal of a Binary Tree using Iteration
  10. 10Reverse Level Order Traversal of a Binary Tree using Recursion
  11. 11Find Height of a Binary Tree
  12. 12Find Diameter of a Binary Tree
  13. 13Find Mirror of a Binary Tree
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree
GraphsGraphs46
  1. 1Breadth-First Search in Graphs
  2. 2Depth-First Search in Graphs
  3. 3Number of Provinces in an Undirected Graph
  4. 4Connected Components in a Matrix
  5. 5Rotten Oranges Problem - BFS in Matrix
  6. 6Flood Fill Algorithm - Graph Based
  7. 7Detect Cycle in an Undirected Graph using DFS
  8. 8Detect Cycle in an Undirected Graph using BFS
  9. 9Distance of Nearest Cell Having 1 - Grid BFS
  10. 10Surrounded Regions in Matrix using Graph Traversal
  11. 11Number of Enclaves in Grid
  12. 12Word Ladder - Shortest Transformation using Graph
  13. 13Word Ladder II - All Shortest Transformation Sequences
  14. 14Number of Distinct Islands using DFS
  15. 15Check if a Graph is Bipartite using DFS
  16. 16Topological Sort Using DFS
  17. 17Topological Sort using Kahn's Algorithm
  18. 18Cycle Detection in Directed Graph using BFS
  19. 19Course Schedule - Task Ordering with Prerequisites
  20. 20Course Schedule 2 - Task Ordering Using Topological Sort
  21. 21Find Eventual Safe States in a Directed Graph
  22. 22Alien Dictionary Character Order
  23. 23Shortest Path in Undirected Graph with Unit Distance
  24. 24Shortest Path in DAG using Topological Sort
  25. 25Dijkstra's Algorithm Using Set - Shortest Path in Graph
  26. 26Dijkstra’s Algorithm Using Priority Queue
  27. 27Shortest Distance in a Binary Maze using BFS
  28. 28Path With Minimum Effort in Grid using Graphs
  29. 29Cheapest Flights Within K Stops - Graph Problem
  30. 30Number of Ways to Reach Destination in Shortest Time - Graph Problem
  31. 31Minimum Multiplications to Reach End - Graph BFS
  32. 32Bellman-Ford Algorithm for Shortest Paths
  33. 33Floyd Warshall Algorithm for All-Pairs Shortest Path
  34. 34Find the City With the Fewest Reachable Neighbours
  35. 35Minimum Spanning Tree in Graphs
  36. 36Prim's Algorithm for Minimum Spanning Tree
  37. 37Disjoint Set (Union-Find) with Union by Rank and Path Compression
  38. 38Kruskal's Algorithm - Minimum Spanning Tree
  39. 39Minimum Operations to Make Network Connected
  40. 40Most Stones Removed with Same Row or Column
  41. 41Accounts Merge Problem using Disjoint Set Union
  42. 42Number of Islands II - Online Queries using DSU
  43. 43Making a Large Island Using DSU
  44. 44Bridges in Graph using Tarjan's Algorithm
  45. 45Articulation Points in Graphs
  46. 46Strongly Connected Components using Kosaraju's Algorithm

Count Subarrays with Given Sum using Prefix Sum and HashMap Optimal Solution

Problem Statement

Given an integer array arr and a target sum k, your task is to find the total number of continuous subarrays whose elements add up to exactly k.

A subarray is a sequence of elements that appears in the same order in the array and is contiguous. The same element can be included in multiple subarrays if it appears in different positions.

This problem is common in applications involving range-based queries, financial analysis, and interval sum counting.

Examples

Input Array Target Sum (k) Count of Subarrays Description
[1, 2, 3] 3 2 Subarrays: [1, 2], [3]
[1, 1, 1] 2 2 Subarrays: [1, 1] (at two different positions)
[3, 4, 7, 2, -3, 1, 4, 2] 7 4 Subarrays: [3,4], [7], [4, 2, 1], [1, 4, 2]
[1, -1, 0] 0 3 Subarrays: [1, -1], [0], [1, -1, 0]
[] 0 0 Empty array has no subarrays
[0, 0, 0] 0 6 All possible subarrays (of lengths 1 to 3) sum to 0
[1, 2, 3] 10 0 No subarray adds up to 10
[5] 5 1 Single element equal to k
[5] 3 0 Single element not equal to k

Visualization Player

Solution

Step-by-Step Solution for Beginners: Count Subarrays with Sum = k

1. Understand the Problem First

We are given an array of integers and a target number k. We are asked to count how many continuous subarrays have a sum equal to k.

Let’s take an example to better understand this:

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

Explanation: The subarrays [1, 2] and [3] both sum to 3.

2. Strategy: Prefix Sum + Hash Map

Instead of checking every possible subarray (which takes O(n²) time), we will use a smarter approach using:

  • Prefix Sum: Keep track of running total as we move through the array.
  • Hash Map: Store how many times each prefix sum has occurred.

3. How It Works Step by Step

Let’s say we’re at index i and the sum of elements from the beginning up to this point is prefixSum. We are looking for how many previous prefix sums satisfy:

prefixSum - k = previousPrefixSum

If such a previousPrefixSum was seen earlier, then a subarray ending at index i has a total sum of k. We can count all such prefix sums using the hash map.

4. Solve the Given Example

Input: nums = [1, 2, 3], k = 3
Let’s walk through it:


Initialize:
prefixSum = 0
count = 0
map = {0: 1}  (to handle subarrays starting from index 0)

Loop through the array:
- num = 1 → prefixSum = 1  
  → prefixSum - k = -2 → not in map  
  → add 1 to map → map = {0:1, 1:1}

- num = 2 → prefixSum = 3  
  → prefixSum - k = 0 → found in map!  
  → count += 1 (map[0]) → count = 1  
  → add 3 to map → map = {0:1, 1:1, 3:1}

- num = 3 → prefixSum = 6  
  → prefixSum - k = 3 → found in map!  
  → count += 1 (map[3]) → count = 2  
  → add 6 to map → map = {0:1, 1:1, 3:1, 6:1}

Final answer = 2

5. Edge Cases

  • Empty Array: No elements means no subarrays. Output = 0.
  • Negative Numbers: The prefix sum method works even if elements are negative.
  • Zeros: In cases like [0, 0, 0] and k = 0, every subarray sums to 0. We count all valid ones.
  • Multiple Matches: If a prefix sum appears multiple times, all such matches should be added to the count.

6. Why This Approach Works Efficiently

Instead of checking every pair of start and end points for subarrays, we maintain a running prefix sum and look up how many times prefixSum - k has occurred before. This lookup is done in constant time using a hash map.

This brings down the time complexity from O(n²) to O(n), which is very efficient even for large arrays.

Algorithm Steps

  1. Given an array arr and a target k.
  2. Initialize a prefix sum curr_sum = 0 and a hash map prefix_count to store frequency of prefix sums.
  3. Initialize count = 0.
  4. Iterate through the array:
  5. → Add current element to curr_sum.
  6. → If curr_sum == k, increment count by 1.
  7. → If curr_sum - k exists in prefix_count, add its frequency to count.
  8. → Update the frequency of curr_sum in prefix_count.
  9. Return the total count.

Code

Python
JavaScript
Java
C++
C
from collections import defaultdict

def count_subarrays_with_sum(arr, k):
    prefix_count = defaultdict(int)
    curr_sum = 0
    count = 0

    for num in arr:
        curr_sum += num
        if curr_sum == k:
            count += 1
        if (curr_sum - k) in prefix_count:
            count += prefix_count[curr_sum - k]
        prefix_count[curr_sum] += 1

    return count

# Sample Input
arr = [1, 1, 1]
k = 2
print("Count of Subarrays:", count_subarrays_with_sum(arr, k))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Each element is visited exactly once, and all operations (hashmap lookups and updates) take constant time.
Average CaseO(n)On average, the algorithm maintains a prefix sum hashmap and performs constant-time operations per element.
Worst CaseO(n)Even in the worst case, the array is traversed only once and hashmap operations remain O(1), resulting in linear time complexity.

Space Complexity

O(n)

Explanation: A hashmap is used to store the frequency of prefix sums, which can grow up to the size of the input array in the worst case.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...