Counting Subarrays with Sum K using Prefix Sum and Hashmap

Day 15 of being consistent with DSA Today’s problem: 𝗦𝘂𝗯𝗮𝗿𝗿𝗮𝘆 𝗦𝘂𝗺 𝗘𝗾𝘂𝗮𝗹𝘀 𝗞 The goal is to count the number of continuous subarrays whose sum equals k. I solved it using the prefix sum + hashmap pattern, keeping track of running sums and checking if a previous sum exists that helps form k. Instead of checking all subarrays, the idea is to reuse previously seen sums to count valid subarrays efficiently. One thing I learned:- Storing intermediate results (like prefix sums) can reduce a brute force O(n²) solution to O(n). 𝗧𝗶𝗺𝗲 𝗰𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 -> 𝗢(𝗻) 𝗦𝗽𝗮𝗰𝗲 𝗰𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 -> 𝗢(𝗻) Neetcode Link:- https://lnkd.in/eRCy5_VA Github Link:- https://lnkd.in/eqnHgyHM #SoftwareEngineering #DSA #ProblemSolving #LearningInPublic #NeetCode250

  • text

To view or add a comment, sign in

Explore content categories