How to get better with algorithms with the help of Leetcode

Janevit Dechnumbuncharchai
LifeatRentSpree
Published in
9 min readNov 3, 2021

First of all, I want to explain what algorithm is…

or not.

Because we all already know what algorithm is, don’t we? 😉

So, let’s just skip to the part where we get to talk about how cool an efficient and better algorithm can do for us.

(But really, if you want to know, there’s a wikipedia page.)

Table of Contents

  • What can better algorithms do for us?
  • What are some examples of improved algorithms?
  • How can Leetcode help?
  • Other features on Leetcode?
  • Other sites in similar?
  • What about Geeksforgeeks?
  • Is it really necessary?

What can better algorithms do for us?

I will bring up an example here:

Let’s say, I have a data set of 10,000 elements, and time complexity of our algorithm is O(n²), that would take 100,000,000 operations to finish the job.

(To learn more about Time Complexity and Big O notation.)

Now, if 1 operation took 1 milliseconds, that algorithm would take 100,000 seconds to finish. In contrary, a O(n) algorithm would only take 10 seconds.

(Time calculations here are just assumption; there actually are more factors to consider than only time complexity.)

There are times that all those 100,000,000 steps are necessary, but there are also times that are not.

Let’s move to the next step, in a more practical way: what if we want to find out whether there’s a duplicate in the data set?

The easiest way may be to loop through the set while checking every element to see if they’re the same — that’s O(n²).

And here, I’m gonna argue that not all those 100,000,000 steps are necessary.

Let’s look at the data set once again, [5, 3, 2, 10, 15, 1, 2, 9, 8, 7]. You can see that the data is all scattered, random and having no order whatsoever. But, what if I say there’s a way to pre-process the data set to reduce searching to O(n)?

You can pause here if you wanna take time to think about it first.

We can achieve that by applying a O(n log n) sorting algorithm beforehand, the data set will then be in order, [1, 2, 2, 3, 5, 7, 8, 9, 10, 15]. As you can see, a pattern has appeared; duplicates are arranged right next to each other, leaving the searching part to a straightforward way; that is to loop until find same value as the previous element, a O(n) one. This will reduce the overall time complexity — including pre-process — to O(n log n), approximately 1,700,000 steps, 58x less!

And for an extra bit, to really achieve O(n) overall time, in a case that we can afford to trade-off space complexity of O(n), we can store values we see while we iterate the data set, so when we move to next element, we can check whether we have this value stored, whether we’ve seen this one before, then we can decide if there’s a duplicate in the data set. This can even be done within the scope of O(n) time, coming down to only 10,000 steps, much faster, or we could say, lightning fast — but only if we can afford the trade-off.

Common Data Structure Operations; some can surprise you.
Array Sorting Algorithms, beware of the space complexity.

What are some examples of improved algorithms?

Binary search

In a scenario of which is heavily-dependent on searching, low on modifying existing data set, rather than conducting a search in O(n) scope every single time, O(n log n) binary search can really make an impact. But, one trade-off would be we need to store and keep our data set in a sorted order.

xkcd’s Tree and Heap, just to portray how to keep things in sorted order.

Floyd’s tortoise and hare

An improved way of detecting cycle, rather than storing what we’ve seen in memory — costing O(n) space — is to use 2 pointers and let them race ‘till one catches up, that’s O(1) space.

Floyd’s “tortoise and hare” cycle detection algorithm, applied to the sequence 2, 0, 6, 3, 1, 6, 3, 1, …

Knuth–Morris–Pratt algorithm

s = sentence’s length, p = pattern to search for.

A string-searching algorithm that performs in O(s) scope, better than the native one that runs in O(p * s). But this trick requires O(s) space and a preprocess of O(s) time.

How can Leetcode help?

Disclaimer: this is not an advertisement. I know it sounds like one, but they don’t pay me…

A reliable source recommended Leetcode for me to try out, and I’ve concluded that it has made my learning journey a lot easier.

Leetcode is a platform that presents us with coding problems, so people can practice and improve their skills.

General features of this type of platform are:

  • There are a lot of problems with different categories.
  • A judge to run and grade our code.
  • Solutions to those problems.
  • A forum for the community to discuss problems.

Most sites should already cover those, but let me highlight on some features that I think Leetcode shines on.

1. Lots, and lots of problems.

There are currently 1,794 problems and a lot of filter options.

There is a total of 1,794 problems and still counting, covering a wide range of commonly-known topics, such as: Binary Search, DFS, Dynamic Programming, Graph, Greedy, Hash Table or Sort, so when you decide to focus on some topics, you can go through the list pick one to practice from. Apart from choosing by related topics, the problems can also be filtered and sorted by title, difficulty, top-100-liked or curated lists, so you will know what you’re dealing with.

Curated explore page.
Description of Two Sum problem.

More on the problem aspect, I personally think that Leetcode’s problems usually have a comprehensive description with test cases and some constraints, so it’s rather easy to understand and get started.

There will reveal hints and solution of Two Sum after this point, so if you want to solve it, do it first before continue.

Related Topics and Hints, if provided.

Other than that, there’s a helper below the description (for some problems); they serve as hints for those who want a little help but don’t wanna go to the extent of full solution yet.

Similar problems of Two Sum.

To add a nice touch, Leetcode also provides similar list of problems of each problem to be able to explore more on the topic, so I’m sure you’ll find what you’re looking for, and even better, master it.

Available topics to choose from.

2. Solution (The link is an example of Solution of Two Sum)

Solution of Two Sum provides different ways to solve the problem.
Quick Navigation on top provides an overview of Solution

Leetcode’s Solution is a curated content designed for better understanding of a problem. It usually provides multiple — if not all — possible ways of how to solve the problem, usually with code and explanation in detail with an analysis of time and space complexity, but not all Solution are perfect, so there’s a rating system covering them to give a glimpse of what this Solution will look like, whether it’s good enough or poorly written. Also, in a case that Solution itself isn’t clear enough, there’s also Comment section down below the page for users to comment their opinion about the Solution.

3. Discuss (The link is an example of Discuss of Two Sum)

Discuss of Two Sum, ranked by Most Votes

And if Solution still isn’t enough, or none available in the first place, there’s Discuss provided for each problem as a forum for the community to come together and help each other out. Leetcode’s Discuss is a place for users to share their codes, solutions or ask questions about the associated problem, so Discuss is easily one of the main reasons why I recommend Leetcode over other sites. I know it’s a must-have feature for sites of this category, but due to high number of active users, paired with upvote/downvote and tagging system, Leetcode’s Discuss itself can be pretty helpful most of the time. Some codes or solutions can sometimes be hard to comprehend — some are actually just to show off — but there still are plenty more to choose to learn from, and there definitely are unbelievably talented people posting solutions on there. Extra point is that even when Solution of a problem is locked by the premium feature, Discuss will always be available for you to look for answers. 😉

I know that when it comes to a forum-type feature, there’s no escape from toxic aspects of it, but I personally believe that the prominent characteristics of Leetcode’s Discuss can overshadow them and worth your time.

4. Monthly Challenge

March LeetCoding Challenge 2021

Is a monthly collection of problems that will be revealed everyday; it can potentially help reminding you to practice coding everyday, with little reward of LeetCoins to redeem in the Store — there’s not much there though.

What about other features on Leetcode, aren’t they worth of being talked about?

They are, in fact, but they shine most in the aspect of getting ready for an interview.

  • Forum: Interview Question is for Leetcode users to share problems that they have encountered in past interviews.
  • Forum: Interview Experience is for users to share experience when they went through an interview process, especially in a detailed format, may include interview problems and advices from the post’s owner.
  • Forum: Compensation is for sharing compensation package from tech companies for information.
  • Mock Interview lets you prepare in an environment of time-pressured, no hints or clues, or even how difficult the problems are, in levels.
  • Premium Plan is a subscription system to unlock premium added features and content on Leetcode such as: video solutions, debugger, faster judge, problems sorted by companies, mock interview curated for top companies.

What about other sites in similar?

Familiar names are:

  • Google’s coding competitions is seasonal, but you can try out past contests.
  • Clash of Code, which I haven’t experienced firsthand. In my perspective, it brings in the fun of playing a game into coding, consisting of short battles — they say — of coding problems to challenge other people playing at the same time. Sounds fun.
  • Hackerrank is not my taste. I’ve managed a contest one time and realized that some problems aren’t from Hackerrank itself. Some don’t support every well-known languages. Worst, the test cases aren’t even reliable enough to distinguish between O(n) and O(n²).
  • Topcoder
  • Codewars

I didn’t see Geeksforgeeks on the list, but I see it every time I google something. Why?

Geeksforgeeks is a great place for solutions when you know what you’re looking for, but an obvious pain point is that it’s too overwhelming. There’s information everywhere; even for 1 solution, there’re a plenty of articles about it. So, it’s easy to get lost without realizing that you’re learning everything about one topic, or nothing at all.

Let’s be honest, is it really, really necessary?

xkcd’s Traveling Salesman Problem, funny, isn’t it?

To answer this question, we’d have to consider some conditions first:

  • If you don’t care about performance, sure, it isn’t.
  • If you can’t afford space trade-off, some algorithms aren’t even usable.
  • If the program always deal with a small set of data, it won’t affect much either.

But, to be honest, I still recommend everyone to learn to code with efficient algorithms. Even if it isn’t used in the work you do everyday, it’ll definitely revise the way we think and the way we code, sometimes it feels like it’s engraved into the procedure of how we solve something: could searching for this be done in O(n log₂ n) time? Could doing a pre-process on that reduce waiting time to O(n)? Is adding this gonna affect the overall performance time? How can that be improved?

I know it’s an extra step to take, but I definitely think it’s worth it, because once you know how to code better, why not do it? 😉

--

--