Prefix Sum + HashMap for Subarray Sum Equals K Problem

DSA Day 11 – Prefix Sum + HashMap Pattern Today I solved the “Subarray Sum Equals K” problem on LeetCode. Problem: Given an array and an integer k, find the total number of subarrays whose sum equals k. Approach Used: -> Used Prefix Sum to keep track of cumulative sum -> Used HashMap to store frequency of prefix sums -> At each step, checked if (currentSum - k) exists in map -> If yes → added its frequency to count Time Complexity: -> O(n) Space Complexity: -> O(n) Key Learning: -> Prefix Sum helps convert subarray problems into simple calculations -> HashMap allows constant time lookup for previous sums -> Instead of checking all subarrays (O(n²)), we optimize to O(n) What I Realized: Earlier I used brute force for subarrays, but today I understood how prefix sum + hashmap eliminates nested loops completely. This pattern is powerful for many subarray problems. Thanks to Pulkit Aggarwal sir for guiding me in DSA and helping me understand problem-solving patterns. Consistency is turning into real problem-solving ability. #DSA #LeetCode #Java #ProblemSolving #CodingJourney #100DaysOfCode

  • text

To view or add a comment, sign in

Explore content categories