Subarray Sum Equals K Java Solution

𝐒𝐭𝐨𝐩 𝐨𝐯𝐞𝐫-𝐜𝐨𝐦𝐩𝐥𝐢𝐜𝐚𝐭𝐢𝐧𝐠 𝐒𝐮𝐛𝐚𝐫𝐫𝐚𝐲 𝐩𝐫𝐨𝐛𝐥𝐞𝐦𝐬! Most developers brute-force these with O(n²). 🐢, but that won't pass a Senior Dev interview. I’m starting a daily series: 𝐓𝐡𝐞 𝐓𝐞𝐜𝐡 𝐓𝐫𝐞𝐤🧗♂️. One LeetCode pattern, one simple story, one optimized solution. 𝐓𝐨𝐝𝐚𝐲'𝐬 𝐓𝐨𝐩𝐢𝐜: 𝐒𝐮𝐛𝐚𝐫𝐫𝐚𝐲 𝐒𝐮𝐦 𝐄𝐪𝐮𝐚𝐥𝐬 𝐊 I used to find Prefix Sums confusing until I visualized them as a mountain hike. Meet 𝐒𝐮𝐦𝐦𝐢𝐭 𝐒𝐚𝐦—he doesn’t measure the trail twice. He just remembers where he’s been. 𝐓𝐡𝐞 𝐋𝐨𝐠𝐢𝐜: Current Elevation - Goal = A Previous Landmark? If yes, you just found your path. 𝐓𝐡𝐞 𝐎(𝐧) 𝐉𝐚𝐯𝐚 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧: public int subarraySum(int[] nums, int k) { int count = 0, sum = 0; HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 1); // Starting at base camp for (int n : nums) { sum += n; // Climbing higher if (map.containsKey(sum - k)) { count += map.get(sum - k); // Found a path! } map.put(sum, map.getOrDefault(sum, 0) + 1); // Mark the map } return count; } #Java #SoftwareEngineering #DataStructures #LeetCode #CodingTips #TechCommunity

  • text

Mastered the Prefix Sum? Now see how it evolves! I just dropped Day 2, where we tackle the Sliding Window to find Maximum Sum Subarrays in O(n). Don't miss it! 👇 https://www.garudax.id/posts/deviprasadpati_java-codinglife-algorithms-share-7454385225280802816-Hf0N?utm_source=share&utm_medium=member_ios&rcm=ACoAADON3r4BIe7r-QXY7S1sm1X4rs_Y2Ch6R2U

Like
Reply

To view or add a comment, sign in

Explore content categories