Backtracking
Backtracking and Constraint Search
Backtracking is search with an undo. You commit to a choice, recurse, and if the choice cannot lead anywhere valid you unwind it and try the next. Described that way it sounds simple; written as recursive code with a mutable state that has to be restored precisely, it is a common source of confusion.
This is the topic where watching execution helps most, because the shape of the algorithm is a tree being walked and pruned. Seeing N-Queens place a queen, hit a conflict several rows later and unwind makes the undo step concrete, and the same structure then reads clearly in subsets, permutations and Sudoku.
Interactive lessons
Languages (JS, TS, Python, Java, C, C++)
Backtracking lessons
Backtracking time and space complexity compared
Best, average and worst-case running time and extra space for every backtracking lesson, as each lesson derives them.
| Lesson | Best | Average | Worst | Space |
|---|---|---|---|---|
| Introduction | Exponential (depends on branching factor and depth) | Exponential | O(B^D) where B is branching factor, D is depth (e.g., O(N!) or O(2^N)) | O(D) (Recursion stack depth) |
| Subsets | O(N * 2^N) | O(N * 2^N) | O(N * 2^N) | O(N) |
| Permutations | O(N * N!) | O(N * N!) | O(N * N!) | O(N) (Recursion stack) |
| N-Queens | O(N!) | O(N!) | O(N!) | O(N) (Recursion stack + board storage) |
| Sudoku Solver | O(9^M) (M = empty cells) | O(9^M) | O(9^M) | O(M) (recursion stack) |
| Rat in a Maze | O(3^(N^2)) | Exponential | O(3^(N^2)) | O(L * N^2) where L is path length |
Continue the DSA curriculum
Backtracking is one of 12 topics in the interactive DSA visualizer curriculum. Once this topic is comfortable, the coding interview pattern library reorganises the same material around the patterns interview questions are built on.
Every other DSA visualizer
Data Structures · 28 lessons
- StackFree
- QueueFree
- Deque
- Circular Queue
- Priority Queue (ADT)
- Tree Traversal
- Binary Tree
- Binary Search Tree
- AVL Tree
- Trie (Prefix Tree)
- Segment Tree
- Fenwick Tree
- Red-Black Tree
- Singly Linked List
- Doubly Linked List
- Circular Linked List
- Graph RepresentationFree
- Breadth First SearchFree
- Depth First Search
- Topological Sort
- Cycle Detection
- Connected Components
- Bipartite Graph
- Dijkstra's Algorithm
- Bellman-Ford Algorithm
- Minimum Spanning Tree
- Floyd-Warshall Algorithm
- Bridges & Articulation Points
