TL;DR Think before you code.

When I encounter a difficult coding challenge (think LeetCode, HackerRank, or TopCoder) I immediately start thinking out loud about how to solve it.

After a minute of brainstorming it is easy to think, “Oh, I kind of get what I’m supposed to do, so I’ll just start writing code and the solution will work itself out.”

When I start coding a solution with this level of uncertainty I just get more confused by trying to write code.

This approach is like a downward spiral, because the code is messy at first and just gets messier as I try to fix issues without fully understanding what the solution should look like. It’s like digging oneself into a hole or painting oneself into a corner. Most of the time it’s easier to just delete all the code and start fresh rather than working from these ill-conceived, muddled bits of code.

There is a better way.

It is worth it to take the time to truly consider each step of the solution before trying to code it. The solution should be crystal clear in one’s mind before writing a single line of code.

A couple things are prerequisite for this type of thinking:

  1. A focused (non-tired) mind. True story #1: I tried to implement a complex sorting algorithm on 2 hours of sleep one time… yeah, that didn’t go so well.
  2. Knowledge of the fundamental CS concepts required to solve the problem. True story #2: I once tried solving a problem that dynamic programming was particularly well suited for before I knew anything about DP. It was like trying to hammer a nail into the wall with a hotdog bun.

Happy thinking (and then coding)!