I’ve been writing software professionally for 26 years, and until last week I had never attempted to solve a LeetCode problem.
If you haven’t heard of it, LeetCode is a website with thousands of programming puzzles. Each one is a small, self-contained problem, like “find the middle value of two sorted lists of numbers.” You write a solution in the browser, and the site runs it against a hidden set of test cases and tells you whether it’s right and how fast it is compared to other submissions. For years it was where engineers went to cram for job interviews, because a lot of tech companies tested candidates with exactly these puzzles.
I’m not interviewing for anything. I signed up because a code puzzle sounded like a fun way to keep my brain sharp. In the spirit of that, I wrote every line of code myself. I picked a Hard problem as my first exercise, and it turned into a week-long experiment that confirmed my thoughts on what coding is now.
The problem
The puzzle was “Median of Two Sorted Arrays.” You get two lists of numbers, each already sorted, and you return the median of everything combined. Each list holds up to 1,000 numbers, and the values run from -1,000,000 to 1,000,000.
That part is easy. The catch is one line in the problem statement: the solution should run in O(log(m+n)) time.
In plain terms, you aren’t allowed to look at every number. Each step has to throw away a big chunk of what’s left, the way you’d find a name in a phone book by opening to the middle and discarding half. The obvious approach, combining the lists and picking the middle, is off the table.
Attempt one: confident and wrong
My first idea was to search over the values instead of the positions. Guess a number, count how many elements sit on each side of it in both lists, and move the guess toward the heavy side until the counts balance.
It took me about five hours to get working. It passed LeetCode’s examples, my own test cases, and a 2,000-element stress case that ran instantly. I was pretty pleased with myself.
Then I had Claude fuzz test it. Fuzz testing means throwing huge numbers of random inputs at your code and comparing every answer against a dumb but obviously correct version. Out of a couple hundred thousand random cases, about 21% failed. Every failure involved duplicate values. With [4] and [3,3], my code returned 3.5 when the answer is 3.
So I patched it. The first patch got failures down to 8%. The second fixed every case I targeted and pushed failures back up to 14%. That’s when I stopped. Every patch was guessing about a situation the core logic should never have produced. I had four rescue branches wrapped around one wrong idea: my test asked “are the counts on each side equal?”, and with duplicates that question often has no exact yes. I’d been patching complexity on top of a structural problem, and I’ve watched enough real projects do that to know how it ends. I scrapped it.
Attempt two: the ties fight back
The second design started by taking an actual element from near the middle of each list as a candidate, binary search where it lands in the other list, count what’s on each side, and narrow toward the heavy side until one candidate splits everything evenly. This turned out to be a much better structural base for the code, didn’t require tracking information across iterations, and didn’t require rescue branches.
My fuzz-and-fix loop looked like this:
| Round | Cases failing | What it found |
|---|---|---|
| 1 | 13% | A swapped-limits bug, searches that never finished, crashes |
| 2 | 9% | A shortcut I broke by reordering code |
| 3 | 5% | Ties: many copies of the same value in the middle |
| 4 | 52 of 204,000 | Only large, tie-heavy arrays, so I added a medium-size tier, which found 5,247 more |
| 5 | 16, plus 960 in the new tier | One convergence problem around long runs of a single value |
| 6 | 0 | Nothing |
The best bug of the week was in round 1. I’d initialized each candidate’s search limits from the other list’s length. One character in the wrong place, and it passed tons of tests anyway, because whenever the two lists happen to be the same length, the bug disappears.
The most expensive lesson was a safety net. I’d capped my main loop and recursive call, and quietly returned 0 if they ran out. I spent two hours chasing what I thought was a logic bug before realizing the cap had fired. I knew better than to introduce silent failures, and changed every safety net to throw an exception. From then on every failure told me exactly where it happened.
Two other things made the development loop fast. The fuzzer started shrinking failures automatically, deleting elements until it found the smallest input that still failed, so a 600-element failure became 12 numbers I could trace in the debugger. And every failure became a permanent unit test. I finished with 42 of them.
The final version passed 385,000 checks, including every possible pair of sorted lists up to six long using the values 0 through 3. Then I submitted it to LeetCode: accepted on the first try, 2,099 of 2,099 test cases passed.
Three solutions, one scoreboard
Once my efficient solution was done, I wrote the version I would actually ship at work: copy both lists into one array, sort it, take the middle. It took 15 minutes and passes all the same tests. Then I asked Claude for its own solution. It wrote the textbook approach in seconds, and that code passed the same 204,000-case fuzz test on its first run.
My efficient solution
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public class MedianFinder {
int maxRecursion = 100;
int recursionCount = 0;
public double FindMedianSortedArrays(int[] nums1, int[] nums2)
{
//speed hack step #1: If two arrays do not overlap, go to the common middle and return the median. Includes if one array is blank.
if( nums1.Length == 0 && nums2.Length == 0 )
throw new Exception("Both arrays are empty, there is no median.");
if( nums1.Length == 0 )
return FindMedianOfOneArray(nums2).median;
if( nums2.Length == 0 )
return FindMedianOfOneArray(nums1).median;
if( nums1[nums1.Length-1] <= nums2[0] )
return FindMedianOfTwoArraysNoOverlap(nums1, nums2).median;
else if( nums2[nums2.Length-1] <= nums1[0] )
return FindMedianOfTwoArraysNoOverlap(nums2, nums1).median;
//get median of array #1 and array #2 as starting candidate
(double median, int[] indexes) medianCandidateNums1 = FindMedianOfOneArray(nums1);
(double median, int[] indexes) medianCandidateNums2 = FindMedianOfOneArray(nums2);
//if they are the same number, return that number
if( medianCandidateNums1.median == medianCandidateNums2.median && medianCandidateNums1.indexes.Length == 1 && medianCandidateNums2.indexes.Length == 1)
return medianCandidateNums1.median;
if( medianCandidateNums1.indexes.Length == 2 )
{
//take the lower number as the starting point. We want to work with an actual number from the set, not an average.
medianCandidateNums1.median = nums1[medianCandidateNums1.indexes[0]];
medianCandidateNums1.indexes = [medianCandidateNums1.indexes[0]];
}
if( medianCandidateNums2.indexes.Length == 2 )
{
//take the lower number as the starting point. We want to work with an actual number from the set, not an average.
medianCandidateNums2.median = nums2[medianCandidateNums2.indexes[0]];
medianCandidateNums2.indexes = [medianCandidateNums2.indexes[0]];
}
(int lowerIdxLimit, int upperIdxLimit) cand1Limits = (0, nums1.Length-1);
(int lowerIdxLimit, int upperIdxLimit) cand2Limits = (0, nums2.Length-1);
//if not same, examine how each median lands in the other array via index position binary search, not value binary search
for( int i=0; i<100; i++ )
{
recursionCount = 0;
//find the position of each candidate in the other array
var r1 = BinarySearchForValue(nums1[medianCandidateNums1.indexes[0]], nums2, 0, nums2.Length-1);
//Console.WriteLine($"found = {r1.actuallyFound} idx = {r1.idx}");
//Console.WriteLine($"Searching for {nums1[medianCandidateNums1.indexes[0]]} in nums2, found = {r1.actuallyFound} idx = {r1.idx}");
var r2 = BinarySearchForValue(nums2[medianCandidateNums2.indexes[0]], nums1, 0, nums1.Length-1);
//Console.WriteLine($"Searching for {nums2[medianCandidateNums2.indexes[0]]} in nums1, found = {r2.actuallyFound} idx = {r2.idx}");
var f1 = CheckForFoundMedian((nums1[medianCandidateNums1.indexes[0]],medianCandidateNums1.indexes[0]), r1, nums1, nums2);
//Console.WriteLine($"Found median #1? {f1.foundMedian}, {f1.median}");
var f2 = CheckForFoundMedian((nums2[medianCandidateNums2.indexes[0]],medianCandidateNums2.indexes[0]), r2, nums2, nums1);
//Console.WriteLine($"Found median #2? {f2.foundMedian}, {f2.median}");
if( f1.foundMedian )
return f1.median;
else if( f2.foundMedian )
return f2.median;
bool heavyLeft = f1.left > f1.right;
//median not found, pick a new candidate in the heavy direction
cand1Limits.upperIdxLimit = heavyLeft ? medianCandidateNums1.indexes[0] : cand1Limits.upperIdxLimit;
cand1Limits.lowerIdxLimit = !heavyLeft ? medianCandidateNums1.indexes[0] : cand1Limits.lowerIdxLimit;
//Console.WriteLine($"New cand1Limits: {cand1Limits.lowerIdxLimit}, {cand1Limits.upperIdxLimit}");
double dIdx = (cand1Limits.upperIdxLimit + cand1Limits.lowerIdxLimit) / 2.0;
int newCandIndex = heavyLeft ? (int)Math.Floor(dIdx) : (int)Math.Ceiling(dIdx);
medianCandidateNums1.indexes = [newCandIndex];
medianCandidateNums1.median = nums1[medianCandidateNums1.indexes[0]];
//Console.WriteLine($"Next search index {medianCandidateNums1.indexes[0]} value {medianCandidateNums1.median}");
cand2Limits.upperIdxLimit = f2.left > f2.right ? medianCandidateNums2.indexes[0] : cand2Limits.upperIdxLimit;
cand2Limits.lowerIdxLimit = f2.left < f2.right ? medianCandidateNums2.indexes[0] : cand2Limits.lowerIdxLimit;
//Console.WriteLine($"New cand2Limits: {cand2Limits.lowerIdxLimit}, {cand2Limits.upperIdxLimit}");
dIdx = (cand2Limits.upperIdxLimit + cand2Limits.lowerIdxLimit) / 2.0;
newCandIndex = heavyLeft ? (int)Math.Floor(dIdx) : (int)Math.Ceiling(dIdx);
medianCandidateNums2.indexes = [newCandIndex];
medianCandidateNums2.median = nums2[medianCandidateNums2.indexes[0]];
//Console.WriteLine($"Next search index {medianCandidateNums2.indexes[0]} value {medianCandidateNums2.median}");
}
throw new Exception("Exceeded for loop tries");
}
private (double median, int[] indexes) FindMedianOfOneArray(int[] nums)
{
return FindMedianOfOneArray(nums, 0, nums.Length-1);
}
private (double median, int[] indexes) FindMedianOfTwoArraysNoOverlap(int[] lowerValArray, int[] upperValArray)
{
int totalLength = lowerValArray.Length+upperValArray.Length;
double middleOfIndexes = (totalLength-1) / 2.0;
int[] idxs = [(int)middleOfIndexes];
if( middleOfIndexes - Math.Floor(middleOfIndexes) != 0.0 )
idxs = [(int)Math.Floor(middleOfIndexes), (int)Math.Ceiling(middleOfIndexes)];
int lowerVal = idxs[0] <= lowerValArray.Length-1 ? lowerValArray[idxs[0]] : upperValArray[idxs[0]-lowerValArray.Length];
int upperVal = idxs.Length == 1 ? lowerVal : idxs[1] <= lowerValArray.Length-1 ? lowerValArray[idxs[1]] : upperValArray[idxs[1]-lowerValArray.Length];
return ((lowerVal+upperVal)/2.0, idxs);
}
private (double median, int[] indexes) FindMedianOfOneArray(int[] nums, int lowerIndex, int upperIndex)
{
double middleIndex = ((upperIndex-lowerIndex)/2.0)+lowerIndex;
if( middleIndex - Math.Floor(middleIndex) != 0.0 )
return ((nums[(int)Math.Floor(middleIndex)]+nums[(int)Math.Ceiling(middleIndex)])/2.0, [(int)Math.Floor(middleIndex),(int)Math.Ceiling(middleIndex)]);
else
return (nums[(int)middleIndex], [(int)middleIndex]);
}
private (int idx, bool actuallyFound) BinarySearchForValue(int searchFor, int[] arr, int lowerSearchIdx, int upperSearchIdx)
{
recursionCount++;
if( recursionCount > maxRecursion )
throw new Exception("Hit max recursion");
var m = FindMedianOfOneArray(arr, lowerSearchIdx, upperSearchIdx);
if( arr[m.indexes[0]] == searchFor )
return (m.indexes[0], true); //it could be that there are two indexes found, both equal to val. Does it matter which I return?
else if( m.indexes.Length > 1 && arr[m.indexes[1]] == searchFor )
return (m.indexes[1], true);
else if( m.indexes.Length > 0 && m.median == searchFor )
return (m.indexes[1], false);
if( upperSearchIdx - lowerSearchIdx <= 2 )
{
//The search is at the end. Find the match or the best fit
if( searchFor < arr[lowerSearchIdx] )
return (Math.Max(lowerSearchIdx-1,0), false);
else if (searchFor == arr[lowerSearchIdx])
return (lowerSearchIdx, true);
else if (searchFor > arr[upperSearchIdx])
return (upperSearchIdx+1, false); //+1 bug
else if (searchFor == arr[upperSearchIdx])
return (upperSearchIdx, true);
else if (upperSearchIdx-lowerSearchIdx == 2 && searchFor > arr[lowerSearchIdx+1])
return (upperSearchIdx, false);
else if (searchFor > arr[lowerSearchIdx] && searchFor < arr[upperSearchIdx])
return (lowerSearchIdx+1, (searchFor==arr[lowerSearchIdx+1]));
else
return ((lowerSearchIdx+upperSearchIdx)/2, (searchFor == arr[(lowerSearchIdx+upperSearchIdx)/2]));
}
//No value found yet, and room to search more.
int newLowerSearchIdx = searchFor > m.median ? m.indexes[0] : lowerSearchIdx;
int newUpperSearchIdx = searchFor < m.median ? m.indexes[0] : upperSearchIdx;
return BinarySearchForValue(searchFor, arr, newLowerSearchIdx, newUpperSearchIdx);
}
private (bool foundMedian, double median, int left, int right) CheckForFoundMedian((int val, int idx) medianCandidate, (int idx, bool actuallyFound) otherSearchResult, int[] numsCandidate, int[] numsOther)
{
//set the left/right count based on the array the candidate came from
int leftCount = medianCandidate.idx;
int rightCount = numsCandidate.Length-medianCandidate.idx-1;
//Console.WriteLine($"Initial left/right = {leftCount}/{rightCount}");
//now add in the split from the other array where the value was searched for
leftCount += otherSearchResult.idx;
rightCount += otherSearchResult.idx >= numsOther.Length ? 0 : numsOther.Length-otherSearchResult.idx;
bool otherMatchCountedToRight = rightCount > 0 ? true : false;
//Console.WriteLine($"numsOther.Length {numsOther.Length}, otherSearchResult.idx {otherSearchResult.idx}");
//Console.WriteLine($"After other left/right = {leftCount}/{rightCount}");
//the rightCount logic above, when it finds a match in the other arr, by default counts the matching value as if it's to the right
//of the same number from the candidate arr. There's no reason we can't count the match to the left if it's beneficial
if( otherSearchResult.actuallyFound && rightCount-leftCount >= 2 )
{
rightCount--;
leftCount++;
otherMatchCountedToRight = false;
//keep walking to the right as long as the numbers match the median candidate and its beneficial to walk right
while(rightCount>leftCount && otherSearchResult.idx+1 < numsOther.Length && numsOther[otherSearchResult.idx+1] == medianCandidate.val)
{
rightCount--;
leftCount++;
otherSearchResult.idx++;
}
}
else if( otherSearchResult.actuallyFound && leftCount-rightCount >= 2 )
{
//it could be that numbers to the left are the same number and beneficial to use their position instead
while(leftCount>rightCount && otherSearchResult.idx-1 >= 0 && numsOther[otherSearchResult.idx-1] == medianCandidate.val)
{
rightCount++;
leftCount--;
otherSearchResult.idx--;
}
}
if( leftCount == rightCount )
return (true, medianCandidate.val, leftCount, rightCount);
if( Math.Abs(leftCount - rightCount) <= 1 )
{
//the left and right counts are within 1, so it has to be a pair of indexes making up the average median
if( leftCount > rightCount )
{
//find the next lower index in each array, if it exists, take the one closest in value to the candidate
int? candidateArrLowerIndexVal = medianCandidate.idx-1 >= 0 ? medianCandidate.idx-1 : null;
int? otherArrLowerIndexVal = otherSearchResult.idx-1 >= 0 ? otherSearchResult.idx-1 : null;
if( !candidateArrLowerIndexVal.HasValue )
return (true, (medianCandidate.val+numsOther[otherArrLowerIndexVal.Value])/2.0, leftCount, rightCount);
else if( !otherArrLowerIndexVal.HasValue )
return (true, (medianCandidate.val+numsCandidate[candidateArrLowerIndexVal.Value])/2.0, leftCount, rightCount);
else
{
int odiff = medianCandidate.val-numsOther[otherArrLowerIndexVal.Value];
int cdiff = medianCandidate.val-numsCandidate[candidateArrLowerIndexVal.Value];
int toUse = Math.Abs(odiff) < Math.Abs(cdiff) ? numsOther[otherArrLowerIndexVal.Value] : numsCandidate[candidateArrLowerIndexVal.Value];
return (true, (medianCandidate.val+toUse)/2.0, leftCount, rightCount);
}
}
else
{
//find the next higher index in each array, if it exists, take the one closest in value to the candidate
int? candidateArrHigherIndexVal = medianCandidate.idx+1 < numsCandidate.Length ? medianCandidate.idx+1 : null;
int? otherArrHigherIndexVal = otherMatchCountedToRight && otherSearchResult.idx < numsOther.Length ? otherSearchResult.idx : (otherSearchResult.idx+1 < numsOther.Length ? otherSearchResult.idx+1 : null);
if( !candidateArrHigherIndexVal.HasValue )
return (true, (medianCandidate.val+numsOther[otherArrHigherIndexVal.Value])/2.0, leftCount, rightCount);
else if( !otherArrHigherIndexVal.HasValue )
return (true, (medianCandidate.val+numsCandidate[candidateArrHigherIndexVal.Value])/2.0, leftCount, rightCount);
else
{
int odiff = medianCandidate.val-numsOther[otherArrHigherIndexVal.Value];
int cdiff = medianCandidate.val-numsCandidate[candidateArrHigherIndexVal.Value];
int toUse = Math.Abs(odiff) < Math.Abs(cdiff) ? numsOther[otherArrHigherIndexVal.Value] : numsCandidate[candidateArrHigherIndexVal.Value];
//Console.WriteLine($"odiff {odiff} cdiff {cdiff} touse {toUse}");
return (true, (medianCandidate.val+toUse)/2.0, leftCount, rightCount);
}
}
}
return (false, 0, leftCount, rightCount);
}
}
My practical real-world solution
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public class MedianFinder {
public double FindMedianSortedArrays(int[] nums1, int[] nums2)
{
int[] combined = new int[nums1.Length+nums2.Length];
nums1.CopyTo(combined, 0);
nums2.CopyTo(combined, nums1.Length);
Array.Sort(combined);
return FindMedianOfOneArray(combined).median;
}
private (double median, int[] indexes) FindMedianOfOneArray(int[] nums)
{
return FindMedianOfOneArray(nums, 0, nums.Length-1);
}
private (double median, int[] indexes) FindMedianOfOneArray(int[] nums, int lowerIndex, int upperIndex)
{
double middleIndex = ((upperIndex-lowerIndex)/2.0)+lowerIndex;
if( middleIndex - Math.Floor(middleIndex) != 0.0 )
return ((nums[(int)Math.Floor(middleIndex)]+nums[(int)Math.Ceiling(middleIndex)])/2.0, [(int)Math.Floor(middleIndex),(int)Math.Ceiling(middleIndex)]);
else
return (nums[(int)middleIndex], [(int)middleIndex]);
}
}
Claude’s textbook solution
public class AiSolution {
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.Length > nums2.Length) return FindMedianSortedArrays(nums2, nums1);
int m = nums1.Length, n = nums2.Length;
int half = (m + n + 1) / 2;
int lo = 0, hi = m;
while (lo <= hi) {
int i = (lo + hi) / 2; // elements taken from nums1
int j = half - i; // elements taken from nums2
int left1 = i == 0 ? int.MinValue : nums1[i - 1];
int right1 = i == m ? int.MaxValue : nums1[i];
int left2 = j == 0 ? int.MinValue : nums2[j - 1];
int right2 = j == n ? int.MaxValue : nums2[j];
if (left1 <= right2 && left2 <= right1) {
int leftMax = Math.Max(left1, left2);
if ((m + n) % 2 == 1) return leftMax;
return (leftMax + (double)Math.Min(right1, right2)) / 2.0;
}
if (left1 > right2) hi = i - 1; else lo = i + 1;
}
throw new ArgumentException("Input arrays are not sorted.");
}
}
I benchmarked all three on the largest allowed input, 1,000 numbers per list, averaged over 2,000 random cases:
| Solution | Time to write | Lines of code | Time per call |
|---|---|---|---|
| Real world: combine, sort, take the middle | 15 minutes | 31 | 62 µs |
| Efficient artisanal: mine | 20 hours | About 200 | 5.3 µs |
| AI: Claude’s textbook solution | Seconds | 23 | 0.08 µs |
My version is about 12 times faster than the practical real-world one. That sounds great until you notice two things.
First, the AI version is 65 times faster than mine, in a ninth of the code, and it arrived before I finished reading the problem statement.
Second, all three are fast. The slowest takes 62 millionths of a second. My efficient version saves about 57 µs per call over the 15-minute version, so if my 20 hour week would need about 1.3 billion calls to earn that time back. LeetCode’s own scoreboard agreed it didn’t matter: my 4 ms runtime beat 49.5% of C# submissions, because at this size the timer is mostly measuring .NET starting up.
From job to brain teaser
That scoreboard is the whole argument. Hand-writing a clever algorithm used to be part of the job. Now it’s the slowest, least efficient way to get the result, by a wide margin.
Think about Stack Overflow. For fifteen years it was every developer’s messy tool bin. You showed up with an error message, grabbed the answer that worked, and left. Once an LLM could answer faster and fit the answer to your exact code, most of us stopped visiting without ever deciding to quit. Stack Overflow was purely a means to an end, so when a better means showed up, it faded.
LeetCode is different, because the puzzle is partly the point. Its job as an interview gatekeeper may already be eroding with companies increasingly allowing and even incorporating AI in live interviews. The algorithm-writing itself, the part we used to interview for, has become a brain teaser.
Catch and release
Was it worth a week? Absolutely, just not for the code. I got a hard, honest workout I don’t get from directing agents. I relearned the value of fuzz testing, how a silent safety net can hide a bug for hours, and the discipline to throw away a design instead of patching it forever.
None of those 200 lines will ever run in production. The 8-line version would beat them in any code review, and the AI version beats them on every benchmark. That’s fine. Think of it as catch-and-release programming: you land a solution, admire it for a minute, and throw it back.
I’ll be back for more of these puzzles. Maybe an Easy one next.
