r/leetcode • u/JacketFearless1805 • 7d ago
Intervew Prep Day 27: tackled Longest Subarray with Sum K — hit a wave of DSA nostalgia
Hey everyone,
I finished Day 27 today. I kept the session focused on a single classic problem: Longest Subarray with Sum K. Revisiting this one brought back a lot of nostalgia from the early days of my prep, when prefix sums and sliding windows felt like brand-new tools.
The solution comes down to the constraints on the input elements:
- Positives Only (Optimal Two-Pointer / Sliding Window): When the array contains only positive integers, expanding the right pointer increases the sum and shrinking the left pointer decreases it. This monotonic property lets you find the longest subarray in O(n) time and O(1) space.
- Positives and Negatives (Prefix Sum + Hash Map): Once negative numbers or zeros enter the picture, the sliding window breaks down. Instead, you track the running prefix sum and store the earliest index where each sum appears in a hash map. If
currentSum - kexists in the map, you update the maximum length while keeping the earliest index to maximize subarray size.
It was just one problem today, but seeing how naturally both approaches fit together was a great reminder of how far my problem-solving intuition has come.
See you guys tomorrow for Day 26!
4
Upvotes
1
u/jason_graph 7d ago
Cool. It's good to know when and why sliding window does and doesn't work.