CSE Exam medium Open

Longest Prefix Subarray with Given Sum (Java - Optimized Approach)

P
Posted by Prince Yadav
Longest Prefix Subarray with Given Sum (Java - Optimized Approach)
Description

I am trying to solve a problem where I need to find the length of the longest subarray whose sum equals a given value K. 🔹 Problem Statement: Given an integer array arr[] of size n and an integer K, return the length of the longest subarray whose sum is equal to K. Example: Input: arr = [1, 2, 3, 1, 1, 1, 1] K = 3 Output: 3 Explanation: Subarray [1,1,1] has sum = 3 and length = 3 (maximum possible) 🔹 What I Tried: First, I implemented a brute force approach using nested loops → O(n²) Then I tried using prefix sum + HashMap to optimize to O(n) 🔹 My Approach (Optimized): Maintain a running prefix sum Use a HashMap to store (prefixSum → first occurrence index) If (currentSum - K) exists in map → update max length 🔹 Issue / Doubt: I am confused about: When exactly to store prefix sum in HashMap Why we store only the first occurrence Handling edge case when prefix sum itself equals K 🔹 Expected Help: Clear explanation of optimized approach Step-by-step dry run Best practices for prefix sum problems

DSA Prefix Sum