So I ended up feeling more sick today than I did yesterday. Nevertheless, I decided to do a LeetCode
hard problem today. Let me explain.
When I’m sick, I actually have a hard time concentrating on passive media, such as reading or
watching something. I’ll fall asleep, in fact. So I need to be doing something active. Thus, working on a programming problem is,
somewhat counterintuitively, a good activity for me when I’m sick.
I picked a problem I had encountered years before: Largest Rectange in Histogram, a LeetCode hard. In fact, I first encountered this
problem in a phone screen for Facebook back in 2014. Which is funny: a LeetCode hard in a phone screen.
Gotta respect keeping the bar high. Back then, I hadn’t done enough prep, so I largely got stuck in
the “dang this is hard” loop. Thus, I wanted to take another crack at it.
This time, my goals were fairly modest: arrive at a correct solution that is generally better than
the most naive/brute force. Being rusty, and under the weather, I was doubtful that I would get at the
optimal solution,
as the kind of mental “pattern matching” needed to find optimal solutions takes both a fresh brain
and enough practice.
Even for this at-home retry, I didn’t get out a whiteboard or pad of paper, and ended up regretting it.
I can’t really rapidly try out ideas and examples on a keyboard. Drawing and scribbling ideas is way
faster for me.
Ultimately, I achieved my modest goal. Here is my code. Not great, but not terrible.
That submission beat 32% on runtime and 67% on memory. But it’s clearly too much code to
be an optimal solution. When you’re writing too much code on well-traffic’d problems, it’s usually a clue.
The motivating idea was a simple invariant: a monotonically nondecreasing histogram is easy to
score, so any time we have a decreasing bar, rewrite the histogram to be monotonically nondecreasing
by “closing off” any open rectangles to the left of the decrease. This was done by managing and
rewriting open “ranges”.