Lessons
Abstract
What came to my mind while solving the 45 problems in LeetCode Top Medium.
2026-06-07
- Find a canonical representation. When you're dealing with a
class of objects defined by some constraints, look for a canonical
representation of that class, preferably one that's hashable.
- For instance, all anagrams have the same sorted-letter representation, and so we can use it as a key to group strings by anagrams. See 49. Group Anagrams.
- Another example: in 36. Valid
Sudoku we pick
(r // 3) * 3 + (c // 3)as the box id, a canonical way to represent belonging to one of the 3x3 boxes in a Sudoku grid.
2026-06-08
-
Store the index, not only the value. When you find an element in a Python list (array), you have its index, its positions. So you can move a pointer to this position in \(O(1)\) later without rescanning the array. You must take advantage of this property of Python list. For instance, in 3. Longest Substring Without Repeating Characters, storing the indices along the characters of the characters you scan in the list lets you move the left pointer of the sliding window in \(O(1)\).
-
Build a list of parts and join them to make a string. When iteratively building a string, prefer to build a list of the parts and join them after the loop is finished. It's more efficient than concatenating strings while iterating. See [38. Count and Say](leetcode_top_medium_01_array_and_strings_07_count_and_say.md** for instance.
2026-06-11
- Find the minimal state your program needs to take its next action at any time.
2026-06-12
- Mark visited nodes within the input data. This is \(O(1)\) space
contrary to \(O(n)\) if using a different global set, dictionary,
matrix, etc.
- For instance, in 200. Number of Islands, we can mark visited
cell by sinking land into water like this
grid[r][c] = "0", so that we don't count the same island twice. - For instance, in 79. Word Search, we can mark the cell
board[r][c] = "#"(and storing its value inchvariable) so that we don't consider that cell again for the path we're building. And when we backtrack to build another path, we restore its valueboard[r][c] = chto make it available for the new path.
- For instance, in 200. Number of Islands, we can mark visited
cell by sinking land into water like this