Optimizing Subarray Problems with Prefix Sum and HashMap

📅 Day 12 of My DSA Journey 🚀 Today I solved a problem on finding the length of the longest subarray with a given sum using the Prefix Sum + HashMap technique. 🔢 Problem: Given an array arr = [1,2,3,1,1,1,1] and target = 3, find the length of the longest subarray whose sum equals the target. 💡 Approach: • Maintain a running sum (prefix sum) • Use a hashmap to store first occurrence of each sum • Check if (current_sum - target) exists • Calculate subarray length and track maximum 🧠 Key Learning: Storing the first occurrence of prefix sum helps in getting the longest subarray efficiently in O(n) time. ✅ Output: 3 📌 This problem improved my understanding of optimizing subarray problems using prefix sums. #DSA #Python #CodingJourney #100DaysOfCode #Learning #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories