Most LeetCode problems require some knowledge of algorithms and data structures. But LeetCode problems are also a way to learn algorithms and data structures. So there’s a symbiotic relationship between the problems and the knowledge required to solve them.
Reading a textbook chapter about binary search will help you understand the principles behind it, how to analyze it mathematically, and the steps required to implement it. But it’s difficult to understand binary search well without solving binary search problems. Solving a simple binary search problem like LeetCode 704 is a good way to learn the fundamentals of the algorithm. From there, you can move on to harder problems where you have to integrate the binary search algorithm into a larger solution. As you’re solving a harder problem, you might go back to the textbook description of an algorithm to clarify the details, and then use that information to improve your solution. In this way, you can set up a virtuous cycle where solving problems helps you understand the algorithm, and the algorithm helps you solve problems more effectively.
Writing detailed model solution descriptions can also help you learn algorithms and data structures better. Just as writing a model solution clarifies your understanding of a specific LeetCode problem, it can also help you understand the general principles behind an algorithm. As you write your solutions, use correct terminology and explain how your solution applies a general algorithm to the specific problem you’re writing about. This will make it easier to move on to the next algorithm in a topic-wise list, since your algorithm skills and knowledge won’t be closely tied to one problem.
Besides applying an algorithm to a familiar problem, another key LeetCode skill is selecting the correct algorithm for a problem you haven’t seen before. As you learn algorithms and write solution descriptions, you can take notes from that perspective. For example, you can remind yourself that when the input data for a problem is sorted or can be sorted, consider using binary search. When you’re solving a topic-wise list of problems, you aren’t practicing this skill directly, since you already know which algorithm the problems require. But even with this type of practice, you can look for similarities between the problems, and include these in your notes. Then, when you need to select an algorithm for an unfamiliar problem, you can look through your list of heuristics to get ideas about which algorithm to use.
This year, I’m publishing a series of tips for effective LeetCode practice. To read the tips in order, start with A Project for 2023.