Lam NguyenAlgorithms

Contest Setup

Updated October 12, 2026

Topics
  1. Contest Setup
  2. Binary Search
  3. Dynamic Programming
  4. Range Queries
  5. Priority Queues
  6. Stacks
  7. Hashing
  8. Strings
  9. Graphs and Trees
  10. Graph Theory
  11. Network Flow
  12. Combinatorics
  13. Algebra
  14. Data Structure Design
  15. Performance Optimization
  16. Databases
  17. Selected LeetCode Problems

The files and tools I start every problem with: starter templates for contests, LeetCode, and OI, and small scripts that create, fetch, and test a solution.

From Java to C++ to Python

My template has been rewritten twice, each time in a shorter language. What changed each time was how much bookkeeping I had to type. The shape of the solutions stayed the same. This section is about which parts to shorten, which parts to leave alone, and what to check when reviewing a Python solution.

Java: everything spelled out

The first template was Main.java. Before solve could read a single number it needed a FastScanner, a main that looped over test cases, and a block of static helpers I had written once and carried everywhere: modular add, subtract, multiply, a gcd, a sieve, and a ruffle_sort that shuffles an int[] before sorting it so that an anti-quicksort test could not make Arrays.sort quadratic. Modular exponentiation looked like this:

static long exp(long base, long exp) {
    long result = 1;
    while (exp > 0) {
        if ((exp & 1) == 1) result = multiply(result, base);
        base = multiply(base, base);
        exp >>= 1;
    }
    return result;
}

None of that is hard, and all of it is typing. The template ran to nearly 700 lines, and most of them were there to make up for what the standard library left out.

C++: macros for the loops

The C++ template gets the I/O from cin.tie(0) and the containers from <bits/stdc++.h>. What remains repetitive is the loops, so the macros target exactly those: REP(i, n), FOR(i, a, b), all(x), sz(x). Sorting needs no shuffle, because std::sort is introsort. The exponentiation is the same loop, written once in ModFact.h:

ll binpow(ll a, ll b) {
    a %= MOD;
    ll res = 1;
    while (b) {
        if (b % 2) res = (res * a) % MOD;
        a = (a * a) % MOD;
        b >>= 1;
    }
    return res;
}

Python: the library is the template

In Python, that function is a built-in: pow(a, b, MOD). The inverse is pow(a, -1, MOD). Most of the notebook’s helpers shrink the same way, because Python’s standard library already has them:

C++ Python
prefix-sum loop list(accumulate(a, initial=0))
sort, unique, lower_bound to compress rank = {x: i for i, x in enumerate(sorted(set(a)))}
binpow(a, b), modInverse(a) pow(a, b, MOD), pow(a, -1, MOD)
memo table filled with -1 @cache on the recursive function
map<int, int> cnt Counter(a)
lower_bound, upper_bound bisect_left, bisect_right
priority_queue (max on top) heappush(pq, -x), since heapq is a min-heap
loop over adjacent pairs zip(a, a[1:])
vector<vector<int>>(n, vi(m)) [[0] * m for _ in range(n)]

leetcode.py is the starter. It has these imports, INF and MOD, the dr and dc arrays, and a raised recursion limit. cpnew A leetcode --py copies it, the same way cpnew A leetcode copies the C++ one.

Structures come over as close to the C++ as possible, keeping the same file paths and method names, so a Python file reads next to its header. FenwickTree.py is still 1-indexed with add(i, u) and sum(L, R). SegmentTree.py still recurses on (v, tl, tr), but takes combine and identity as arguments instead of virtual methods. CoordinateCompression.py keeps value_at and rank_of, and replaces the lower_bound with a dictionary lookup.

What stays traditional

The shortcuts above all replace bookkeeping. The control flow is a different matter, and here is a solution to LeetCode 778 that I would write the same way in any of the three languages:

def valid(t: int):
    if grid[0][0] > t: return False
    q = deque()
    q.append((0, 0))
    seen = set()
    seen.add((0, 0))
    while q:
        r, c = q.popleft()
        if r == n-1 and c == n-1: return True
        for i in range(4):
            nr, nc = r + dr[i], c + dc[i]
            if not inrange(nr, nc) or (nr, nc) in seen or grid[nr][nc] > t: continue
            q.append((nr, nc))
            seen.add((nr, nc))
    return False

left, right = 0, n*n
ans = n*n+1
while left <= right:
    mid = left + (right - left) // 2
    if valid(mid):
        ans = mid
        right = mid-1
    else: left = mid+1

A one-liner could replace the four dr, dc neighbors, and bisect could replace the binary search. I keep both explicit for two reasons.

The notebook keeps these shapes in one folder per topic: prefix sums, sliding windows, monotonic stacks, binary search, backtracking, BFS, DFS, Dijkstra, topological sort, and digit DP, next to the Python versions of every C++ structure. Each template is generic, and the problem plugs in through arguments. In BFS.py, bfs_grid takes an ok(r, c) that says which cells can be entered, so walls, water levels, and the grid[nr][nc] > t check above all become one argument, and the loop is never edited. In SlidingWindow.py, the caller keeps the window’s state in add and remove. Every template has a test, and these are the files to write from memory and to check a solution against.

Reviewing a Python solution

Python fails differently from C++. In C++, a mistake usually crashes the program or gives an answer that is obviously wrong. The Python mistakes below all run without an error and give a believable wrong answer, so I check for them every time.

From the Notebook

Implementations from my competitive programming notebook, tagged with their USACO Guide level where they have one.