Skip to content

Practice plan for Python interviews

Use a new problem to test a method, then explain why the method works before you compare solutions. A remembered code fragment does not tell you whether its assumptions match the new problem. Keep a record of the assumption or operation that caused each failed attempt.

  1. Restate the input, required output, and constraints in your own words.
  2. Ask whether the input is sorted, whether duplicates exist, and whether mutation is allowed.
  3. Construct one ordinary example and one boundary example.
  4. Describe a direct solution that you can verify.
  5. Identify its repeated work and choose a structure that removes that work.
  6. State the invariant or recurrence before you write the implementation.
  7. Trace the implementation with the examples before you run it.
  8. Derive time and auxiliary space from the actual Python operations.
  9. Compare the result with the direct solution on small inputs.
  10. Record the failed assumption if either solution disagrees.

If you cannot explain a boundary movement, return to the invariant. Changing the implementation until one example passes can hide an incorrect rule. After you inspect a reference solution, close it and reconstruct the argument from the problem constraints.

These clues suggest methods to investigate; they do not establish that a method is correct. For example, a variable window based on increasing sums needs assumptions that negative values can violate.

Problem property Candidate method Condition to verify
The answer depends on an earlier value or count. Use a dictionary or set. The key must preserve the information the problem needs.
The input is sorted and a pair must satisfy a target. Move two pointers. One comparison must justify discarding a boundary value.
The answer is a contiguous substring or segment. Maintain a sliding window or prefix information. The update rule must remain valid when the boundary moves.
A predicate changes once across an ordered search space. Use binary search. The predicate must be monotone.
The next item is the most recently unfinished item. Use a stack. Last in, first out must match the problem’s dependencies.
The next item is the earliest waiting item. Use a queue. First in, first out must match the required order.
The answer depends on the smallest current candidate. Use a min-heap. The root must represent the candidate that can be removed safely.
The input contains connections or dependencies. Traverse a tree or graph. Define when a node becomes visited and whether components can be separate.
The output contains all valid combinations. Use backtracking. Each choice must have a defined inverse when the algorithm returns.
Several choices reach the same smaller problem. Use dynamic programming. A state must contain enough information to determine future choices.
Each position needs its next greater value. Maintain a monotonic stack. State how equal values affect the pop condition.
Tasks must follow prerequisites. Use topological sorting. A complete order exists only when the directed graph has no cycle.
New edges join components. Use union-find. The problem must not require arbitrary edge deletion or a path itself.
One local choice appears sufficient. Consider a greedy method. Prove that replacing another choice cannot worsen the optimum.
A state depends on two prefixes. Use two-dimensional dynamic programming. Define both indices and initialize the empty-prefix boundaries.

Complete the lesson example before you open its practice problem. The linked problems provide external exercises; their statements and solutions are not reproduced here. Use a repeat exercise to reconstruct the lesson’s reasoning without its source. Use a transfer exercise to adapt that reasoning to changed requirements. The labels below compare the central computation with the lesson, even when a problem uses different names or a different return format. For independent method selection, attempt the mixed problems before reading their hints.

Lesson First exercise Second exercise
Arrays Repeat with Move Zeroes. Transfer with Product of Array Except Self.
Hash maps Transfer with Two Sum. Repeat with Subarray Sum Equals K.
Sets Transfer with Contains Duplicate. Repeat with Longest Consecutive Sequence.
Stacks Repeat with Valid Parentheses. Transfer with Daily Temperatures.
Queues Transfer with Number of Recent Calls. Transfer with Rotting Oranges.
Linked lists Repeat with Reverse Linked List. Transfer with Linked List Cycle.
Trees Repeat with Maximum Depth of Binary Tree. Transfer with Validate Binary Search Tree.
Heaps Transfer with Last Stone Weight. Repeat the retained-largest-values method with Kth Largest Element in an Array.
Graphs Repeat reachability with Find if Path Exists in Graph. Transfer to grid components with Number of Islands.
Pointers and windows Transfer with Valid Palindrome. Repeat with Longest Substring Without Repeating Characters.
Search and intervals Repeat ordered search with Binary Search. Repeat with Merge Intervals.
Backtracking Repeat with Subsets. Transfer to reusable choices with Combination Sum.
Dynamic programming Transfer with Climbing Stairs. Repeat with House Robber.
Monotonic stacks Transfer to value queries with Next Greater Element I. Repeat with Daily Temperatures.
Topological sorting Repeat the cycle decision with Course Schedule. Repeat order construction with Course Schedule II.
Union-find Transfer to a matrix input with Number of Provinces. Transfer to edge selection with Redundant Connection.
Greedy methods Transfer with Assign Cookies. Repeat interval selection with Non-overlapping Intervals.
Two-dimensional dynamic programming Transfer with Unique Paths. Transfer with Longest Common Subsequence.

Test empty inputs when the contract permits them. Test one item, repeated values, no solution, and an answer at either boundary. For pointer algorithms, trace the step where two indices meet. For graph algorithms, include a cycle and an isolated vertex. For recursive algorithms, explain what happens at the base case before you inspect a larger example.

A test should distinguish a correct implementation from a plausible error. An interval example with touching endpoints tests the merge rule. A substring with a repeated character before the current left boundary tests whether that boundary can move backward. A negative array value tests whether a window argument depends on nonnegative values.

Record one concrete cause and one change to your reasoning. Use the record to select the next problem, rather than repeating only the problems you already solve.

Field What to record
Input assumption Record the assumption that the problem does or does not guarantee.
Failing example Save the smallest input that produces an incorrect result.
Invariant Write the statement that should hold after each update.
Incorrect step Identify the update that breaks that statement.
Complexity Count all visits, copies, searches, and sorts in the repaired implementation.
Transfer Choose another problem that requires the same reasoning with different inputs.

The LeetCode problem collection lets you choose additional problems by topic and difficulty. Use unfamiliar problems to test whether you can select the method independently.

The Python library reference documents the containers and functions used in these lessons. Consult the exact operation when a complexity explanation depends on its behavior.