LeetCode Problem Solving — Deep Dive

Constraint-driven algorithm selection

The single most powerful technique for LeetCode is reading the constraints before thinking about the solution. The constraint on n directly tells you the expected time complexity:

ConstraintExpected complexityTypical patterns
n ≤ 10O(n!) or O(2ⁿ)Brute force, backtracking
n ≤ 20O(2ⁿ)Bitmask DP, backtracking with pruning
n ≤ 500O(n³)Floyd-Warshall, triple nested loops
n ≤ 5,000O(n²)DP with 2D table, two nested loops
n ≤ 10⁵O(n log n)Sorting + scanning, binary search
n ≤ 10⁶O(n)Hash map, two pointers, sliding window
n ≤ 10⁹O(log n) or O(√n)Binary search, math

LeetCode typically allows about 10⁸ operations per second for Python. If n = 10⁵ and you use O(n²), that is 10¹⁰ operations — guaranteed Time Limit Exceeded (TLE).

The pattern selection decision tree

START
├── Is input sorted (or can sorting help)?
│   ├── Yes → Two Pointers or Binary Search
│   └── No → continue
├── Is it about subarrays/substrings?
│   ├── Fixed size? → Fixed Sliding Window
│   ├── Variable size? → Variable Sliding Window
│   └── No → continue
├── Is it about trees or graphs?
│   ├── Tree traversal? → DFS (recursive)
│   ├── Shortest path (unweighted)? → BFS
│   ├── Shortest path (weighted)? → Dijkstra
│   └── No → continue
├── Is it about counting/frequency/existence?
│   └── Yes → Hash Map
├── Does it ask for ALL valid combinations?
│   └── Yes → Backtracking
├── Does it ask for min/max with overlapping subproblems?
│   └── Yes → Dynamic Programming
├── Does it ask for k-th element or merging sorted data?
│   └── Yes → Heap
├── Does it involve matching/nesting?
│   └── Yes → Stack
└── Does local optimal = global optimal?
    └── Yes → Greedy

Python optimization techniques for LeetCode

Avoid TLE with these Python-specific tricks

1. Use set and dict instead of list for lookups

# TLE on large inputs
if target - num in nums_list:  # O(n) each time

# Passes
if target - num in nums_set:   # O(1) each time

2. Use collections.deque for BFS

from collections import deque

# list.pop(0) is O(n) — causes TLE on large BFS
queue = deque([start])
node = queue.popleft()  # O(1)

3. Use @lru_cache for top-down DP

from functools import lru_cache

@lru_cache(maxsize=None)
def dp(i, j):
    if i == 0:
        return base_case
    return min(dp(i-1, j), dp(i, j-1)) + grid[i][j]

For problems with mutable arguments (lists), convert to tuples before caching or use bottom-up DP instead.

4. Increase recursion limit for deep recursion

import sys
sys.setrecursionlimit(10**6)

Default is 1,000. DFS on large graphs will hit this. But also consider converting to iterative with an explicit stack.

5. Use bit manipulation for subset problems

# Generate all subsets of n elements
for mask in range(1 << n):
    subset = [nums[i] for i in range(n) if mask & (1 << i)]

6. Use bisect for binary search

import bisect

# Find insertion point in sorted list
idx = bisect.bisect_left(sorted_arr, target)

String building

# O(n²) — string concatenation in loop
result = ""
for c in chars:
    result += c

# O(n) — join
result = "".join(chars)

# O(n) — list append then join
parts = []
for c in chars:
    parts.append(c)
result = "".join(parts)

The 75-problem study roadmap

This curated list covers all major patterns with optimal learning order. Solve them in sequence — each builds on the previous.

Arrays and Hashing (foundation)

  1. Two Sum — hash map lookup
  2. Valid Anagram — frequency counter
  3. Group Anagrams — hash map grouping
  4. Top K Frequent Elements — heap + counter
  5. Product of Array Except Self — prefix/suffix

Two Pointers

  1. Valid Palindrome — converging pointers
  2. 3Sum — sort + two pointers
  3. Container With Most Water — greedy + two pointers
  4. Trapping Rain Water — two pointers or stack

Sliding Window

  1. Best Time to Buy and Sell Stock — minimum tracking
  2. Longest Substring Without Repeating Characters — variable window
  3. Minimum Window Substring — variable window + counter
  4. Longest Repeating Character Replacement — window + frequency

Stack

  1. Valid Parentheses — matching brackets
  2. Min Stack — auxiliary stack tracking minimums
  3. Evaluate Reverse Polish Notation — operand stack
  4. Daily Temperatures — monotonic stack
  1. Binary Search — basic template
  2. Search a 2D Matrix — binary search on virtual array
  3. Koko Eating Bananas — binary search on answer space
  4. Find Minimum in Rotated Sorted Array — modified binary search

Linked Lists

  1. Reverse Linked List — pointer manipulation
  2. Merge Two Sorted Lists — dummy head technique
  3. Linked List Cycle — fast/slow pointers
  4. LRU Cache — hash map + doubly linked list

Trees

  1. Invert Binary Tree — recursive DFS
  2. Maximum Depth of Binary Tree — DFS base case
  3. Same Tree — parallel DFS
  4. Binary Tree Level Order Traversal — BFS
  5. Validate Binary Search Tree — DFS with bounds
  6. Lowest Common Ancestor — recursive LCA
  7. Serialize and Deserialize Binary Tree — BFS encoding

Tries

  1. Implement Trie — node structure
  2. Word Search II — trie + backtracking on grid

Heap / Priority Queue

  1. Kth Largest Element — min heap of size k
  2. Find Median from Data Stream — two heaps
  3. Merge K Sorted Lists — heap merge

Backtracking

  1. Subsets — inclusion/exclusion
  2. Combination Sum — backtrack with reuse
  3. Permutations — swap or visited set
  4. Word Search — grid backtracking

Graphs

  1. Number of Islands — DFS/BFS flood fill
  2. Clone Graph — BFS + hash map
  3. Pacific Atlantic Water Flow — multi-source DFS
  4. Course Schedule — topological sort
  5. Graph Valid Tree — union-find or DFS cycle detection
  6. Word Ladder — BFS shortest path

Dynamic Programming

  1. Climbing Stairs — 1D DP introduction
  2. House Robber — 1D DP with skip
  3. Coin Change — unbounded knapsack
  4. Longest Increasing Subsequence — 1D DP + binary search
  5. Unique Paths — 2D DP grid
  6. Longest Common Subsequence — 2D DP string
  7. Word Break — 1D DP + set lookup
  8. Decode Ways — 1D DP with conditions
  9. Edit Distance — 2D DP classic

Greedy

  1. Maximum Subarray — Kadane’s algorithm
  2. Jump Game — farthest reachable
  3. Jump Game II — greedy BFS layers
  4. Gas Station — circular greedy

Intervals

  1. Merge Intervals — sort + merge
  2. Insert Interval — binary search + merge
  3. Non-overlapping Intervals — greedy removal
  4. Meeting Rooms II — sweep line or heap

Bit Manipulation

  1. Number of 1 Bits — bit counting
  2. Counting Bits — DP + bit manipulation
  3. Missing Number — XOR trick
  4. Reverse Bits — bit shifting

Advanced

  1. Median of Two Sorted Arrays — binary search partition
  2. Alien Dictionary — topological sort
  3. Minimum Interval to Include Each Query — sweep + heap
  4. Regular Expression Matching — 2D DP
  5. Design Twitter — OOP + heap merge
  6. Implement Queue using Stacks — amortized O(1)
  7. Task Scheduler — greedy + math

Common TLE patterns and fixes

Problem patternTLE causeFix
Nested if x in listO(n²)Convert to set → O(n)
String concatenation in loopO(n²)Use "".join() → O(n)
Recursive DP without memoizationExponentialAdd @lru_cache
BFS with list.pop(0)O(n) per popUse deque.popleft()
Recomputing sorted resultsO(n² log n)Sort once, reuse
Creating new lists in recursionO(n) per callUse indices instead

Mock interview protocol

Once you have solved 50+ problems, simulate real interviews:

  1. Set a 45-minute timer.
  2. Pick a random Medium problem you have not seen.
  3. Talk through your approach out loud (even alone).
  4. Write clean code without running it until you think it is correct.
  5. Trace through one example by hand.
  6. Analyze time and space complexity.
  7. Review the editorial afterward, even if you passed.

Record your solve rate. Aim for 70%+ on Mediums within 30 minutes before scheduling real interviews.

One thing to remember: The gap between “I understand the solution” and “I can produce the solution under pressure” is bridged by deliberate practice with a timer. Understanding is necessary but not sufficient — you need fluency, and fluency comes from repetition with intent.

pythonleetcodeproblem-solvingcareeralgorithms

See Also

  • Python Common Interview Patterns The handful of tricks that solve most coding interview problems — no computer science degree required.
  • Ci Cd Why big apps can ship updates every day without turning your phone into a glitchy mess — CI/CD is the behind-the-scenes quality gate and delivery truck.
  • Containerization Why does software that works on your computer break on everyone else's? Containers fix that — and they're why Netflix can deploy 100 updates a day without the site going down.
  • Python 310 New Features Python 3.10 gave programmers a shape-sorting machine, friendlier error messages, and cleaner ways to say 'this or that' in type hints.
  • Python 311 New Features Python 3.11 made everything faster, error messages smarter, and let you catch several mistakes at once instead of stopping at the first one.