Leetcode 1

Let’s talk about the goals developers set for themselves when solving problems on leetcode. Based on those, we’ll settle on the programming language we’ll use to solve them. In my view, there are at least three options:

If we’re talking about the first item — improving your knowledge of algorithms — the choice, in my view, is between two languages: Python and the language you use for your day job.

The Python recommendation is fairly obvious: over the past decade it’s increasingly been used for teaching thanks to its simple, compact syntax. Many problems can be solved in a couple of lines of code there, which will positively affect a programmer’s ability to express their thoughts in code.

Your primary programming language is also a good pick for the same reasons. By framing your solution compactly and expressively, you’ll carry that skill back into your work projects.

A common piece of advice is: don’t try to use the standard library. I think that’s actually fairly harmful advice, and I’d suggest implementing at least two solutions against the same set of tests — one with primitive types and a separate one with the library’s data structures. That’ll help you discover new data structures and functions you’d been skimming past in the docs. In the process, you’ll dig deeper into your primary tool.

When it comes to learning a new programming language, with the goal of getting comfortable with its constructs, problems from leetcode and similar services are very useful.

Here’s a sample solution to one problem. This is how a Go solution might look (and is considered idiomatic):

func containsDuplicate(nums []int) bool {
    ht := make(map[int]struct{})
    for _, v := range nums {
        if _, found := ht[v]; found {
            return true
        }

        ht[v] = struct{}{}
    }

    return false
}

And here are several variations of the same problem using Kotlin’s features:

fun containsDuplicate(nums: IntArray): Boolean = nums.size != nums.groupBy { it }.size

fun containsDuplicate(nums: IntArray): Boolean = nums.size != nums.toSet().size

fun containsDuplicate(nums: IntArray): Boolean = nums.size != nums.distinct().size

Each Kotlin variant fits on a single line, but writing it requires diving into the standard library.

If your goal is to “pad” your rating, I hope the previous two sections persuaded you to reconsider. Preparing and diving into algorithms and languages takes time and energy. What matters is recognizing the value of that preparation for yourself — not taking pride in how many problems you’ve solved.

In the next post we’ll cover recommendations and difficulty levels on leetcode. Thanks for reading and talk soon!