Efficient Subarray Sum Equals K Solution with Prefix Sum + HashMap

Day 11/90 DSA Journey Today I implemented an efficient solution for the classic DSA problem “Subarray Sum Equals K” using Prefix Sum + HashMap. -> Approach: Maintain a running prefix sum while traversing the array. Use a HashMap to store the frequency of prefix sums. At each index, check if (currentSum - k) exists in the map. If it exists, it means there is a subarray ending at the current index with sum = k. -> Key Insight: If sum[j] - sum[i] = k, then the subarray (i+1 to j) has sum k. -> Code Highlights: Initialize map.put(0,1) to handle edge cases. Continuously update frequency of prefix sums. Efficient lookup using HashMap. -> Time Complexity: -> O(n) — We traverse the array only once. -> Space Complexity: -> O(n) — In the worst case, we store all prefix sums in the HashMap. -> Why this is powerful? This approach avoids nested loops (O(n²)) and optimizes the solution using hashing. #DSA #Java #LeetCode #Coding #Hashing #PrefixSum #ProblemSolving

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories