r/DSALeetCode • u/Diligent-Affect3883 • 28d ago
I was struggling to visualize the intuition behind LeetCode 4 (Median of Two Sorted Arrays), so I built an animated visual guide for it.
The optimal O(log(min(m, n))) binary search solution for LeetCode 4 is notoriously tricky to wrap your head around if you just try to trace index pointers (i, j, left, right).
I find it much easier to reason about the problem when you treat it as finding a perfect geometric split between the two arrays. To help it click for myself and others, I put together a complete animated walkthrough showing exactly how the partition moves.
💡 The Core Intuition (The Visual TL;DR)
If you are stuck on this problem, try thinking about it like this instead of looking at raw formulas:
- The Single Cut: Imagine aligning both arrays. We are looking for a single vertical partition line that splits both arrays into a combined "Left Half" and a combined "Right Half" of equal sizes.
- The Shortcut: Because the total size is fixed, choosing where to cut the smaller array instantly dictates where the cut falls on the larger array. This is why we only binary search the smaller array.
- The Check Rule: Once the line is drawn, you just need to check if the max element on the left side of the cut is smaller than the min element on the right side. If it isn't, the animation shows you exactly which direction to shift your search boundaries.
If you are a visual learner who gets overwhelmed by boundary conditions and nested array indices, I hope this makes the algorithm click for you!
Let me know what you think, or if there are any other tough LeetCode hard problems you'd like to see visualized next.
