1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Backtracking
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
15Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Backtracking

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
15Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Backtracking

Overview

Backtracking is an advanced algorithmic technique used for generating all possible solutions (or finding one specific optimal solution) to complex combinatorics problems, such as solving a Sudoku puzzle, the N-Queens problem, or finding all valid permutations of a string.

It is an evolution of standard recursion. In Backtracking, you incrementally build candidates to the solutions. The moment you determine a candidate cannot possibly be completed to a valid solution, you 'backtrack' (undo your last step) and try a different path. This is fundamentally different from a naive Brute Force approach, which generates every single complete possibility before checking if they are valid.

Think of backtracking like navigating a maze. You walk down a path, making choices at intersections. If you hit a dead end, you physically walk backwards (backtrack) to the last intersection and try a different route. By discarding entirely invalid branches of logic early (a concept known as 'Pruning'), backtracking avoids billions of useless computations, making exponentially hard problems solvable.

Syntax

The Backtracking Template: Permutations
java
import java.util.ArrayList;
import java.util.List;

public class Backtracking {
    // Problem: Generate all possible orderings (permutations) of an array
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        backtrack(results, new ArrayList<>(), nums);
        return results;
    }
    
    private static void backtrack(List<List<Integer>> results, List<Integer> currentList, int[] nums) {
        // 1. Base Case: If the current list is full, we found a valid solution!
        if (currentList.size() == nums.length) {
            results.add(new ArrayList<>(currentList)); // Add a COPY of the list
            return;
        }
        
        // 2. Iterate through all possible choices at this step
        for (int i = 0; i < nums.length; i++) {
            // Pruning: Skip numbers we've already used in this permutation
            if (currentList.contains(nums[i])) continue; 
            
            // A. CHOOSE
            currentList.add(nums[i]);
            
            // B. EXPLORE (Recursive call down this path)
            backtrack(results, currentList, nums);
            
            // C. UNCHOOSE (Backtrack!)
            // Remove the last item we added to try the next possible number
            currentList.remove(currentList.size() - 1);
        }
    }
}

Common Pitfalls

  • Failing to make a deep copy of the solution list in the base case. Java passes objects by reference. If you write results.add(currentList), you are adding a reference to the active list. Later, when the algorithm backtracks and clears the list, your stored solution will also become completely empty! You must always do new ArrayList<>(currentList).
  • Forgetting the 'Unchoose' step. The core of backtracking is reverting the state. If you add an item to currentList but don't remove() it after the recursive call returns, your list will just grow infinitely, contaminating all future branches.
  • Poor pruning logic. Backtracking algorithms naturally have factorial O(N!) or exponential O(2^N) time complexities. If you do not actively continue or return when a path is proven invalid early on, your solution will Time Out on competitive programming platforms.

Interview Questions

What is the standard 3-step blueprint for a Backtracking recursive step?

1. Choose: Make a choice and modify the state (e.g., add an item to a list or place a Queen on a board). 2. Explore: Recursively call the function to explore all paths branching from this specific choice. 3. Unchoose: Revert the choice you made in step 1 (remove the item) to reset the state cleanly for the next iteration of the loop.

How does Backtracking differ from pure Depth-First Search (DFS)?

Backtracking is a highly specific, optimized form of DFS. Pure DFS traverses every single node in a tree blindly. Backtracking actively evaluates the current state, and if it violates problem constraints, it 'prunes' the branch, stopping the DFS instantly and retreating up the tree.

Real-World Example

Route Optimization and Logistics. If a delivery driver has 10 packages, an algorithm must find the shortest possible route connecting all 10 houses (a variation of the Traveling Salesperson Problem). Backtracking generates routes: House A -> House B -> House C. If the distance suddenly exceeds a known 'best route', the algorithm backtracks immediately, ignoring the millions of possible routes that branch off that terrible start.

example
java
import java.util.*;

public class RouteOptimizer {
    int shortestDistance = Integer.MAX_VALUE;
    List<String> bestRoute = new ArrayList<>();

    public void findBestRoute(List<String> currentRoute, int currentDistance, List<String> unvisited) {
        // Base Case: All stops visited
        if (unvisited.isEmpty()) {
            if (currentDistance < shortestDistance) {
                shortestDistance = currentDistance;
                bestRoute = new ArrayList<>(currentRoute);
            }
            return;
        }
        
        for (int i = 0; i < unvisited.size(); i++) {
            String nextStop = unvisited.get(i);
            int distanceToNext = calculateDistance(currentRoute.get(currentRoute.size() - 1), nextStop);
            
            // PRUNING: If this path is already longer than our best, stop exploring it entirely!
            if (currentDistance + distanceToNext >= shortestDistance) continue;
            
            // Choose
            currentRoute.add(nextStop);
            unvisited.remove(i);
            
            // Explore
            findBestRoute(currentRoute, currentDistance + distanceToNext, unvisited);
            
            // Unchoose (Backtrack)
            unvisited.add(i, nextStop);
            currentRoute.remove(currentRoute.size() - 1);
        }
    }
    
    private int calculateDistance(String a, String b) { return 10; /* Mock logic */ }
}

Check Your Knowledge

Test your understanding of Backtracking with these quick questions.

Question 1

What is the crucial final step of a backtracking loop that differentiates it from standard recursion?

Question 2

Why is 'Pruning' fundamentally important in backtracking algorithms?

Question 3

When adding a valid combination to a master `results` list in Java, what must you do to prevent data loss?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Backtracking

Overview

Backtracking is an advanced algorithmic technique used for generating all possible solutions (or finding one specific optimal solution) to complex combinatorics problems, such as solving a Sudoku puzzle, the N-Queens problem, or finding all valid permutations of a string.

It is an evolution of standard recursion. In Backtracking, you incrementally build candidates to the solutions. The moment you determine a candidate cannot possibly be completed to a valid solution, you 'backtrack' (undo your last step) and try a different path. This is fundamentally different from a naive Brute Force approach, which generates every single complete possibility before checking if they are valid.

Think of backtracking like navigating a maze. You walk down a path, making choices at intersections. If you hit a dead end, you physically walk backwards (backtrack) to the last intersection and try a different route. By discarding entirely invalid branches of logic early (a concept known as 'Pruning'), backtracking avoids billions of useless computations, making exponentially hard problems solvable.

Syntax

The Backtracking Template: Permutations
java
import java.util.ArrayList;
import java.util.List;

public class Backtracking {
    // Problem: Generate all possible orderings (permutations) of an array
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        backtrack(results, new ArrayList<>(), nums);
        return results;
    }
    
    private static void backtrack(List<List<Integer>> results, List<Integer> currentList, int[] nums) {
        // 1. Base Case: If the current list is full, we found a valid solution!
        if (currentList.size() == nums.length) {
            results.add(new ArrayList<>(currentList)); // Add a COPY of the list
            return;
        }
        
        // 2. Iterate through all possible choices at this step
        for (int i = 0; i < nums.length; i++) {
            // Pruning: Skip numbers we've already used in this permutation
            if (currentList.contains(nums[i])) continue; 
            
            // A. CHOOSE
            currentList.add(nums[i]);
            
            // B. EXPLORE (Recursive call down this path)
            backtrack(results, currentList, nums);
            
            // C. UNCHOOSE (Backtrack!)
            // Remove the last item we added to try the next possible number
            currentList.remove(currentList.size() - 1);
        }
    }
}

Common Pitfalls

  • Failing to make a deep copy of the solution list in the base case. Java passes objects by reference. If you write results.add(currentList), you are adding a reference to the active list. Later, when the algorithm backtracks and clears the list, your stored solution will also become completely empty! You must always do new ArrayList<>(currentList).
  • Forgetting the 'Unchoose' step. The core of backtracking is reverting the state. If you add an item to currentList but don't remove() it after the recursive call returns, your list will just grow infinitely, contaminating all future branches.
  • Poor pruning logic. Backtracking algorithms naturally have factorial O(N!) or exponential O(2^N) time complexities. If you do not actively continue or return when a path is proven invalid early on, your solution will Time Out on competitive programming platforms.

Interview Questions

What is the standard 3-step blueprint for a Backtracking recursive step?

1. Choose: Make a choice and modify the state (e.g., add an item to a list or place a Queen on a board). 2. Explore: Recursively call the function to explore all paths branching from this specific choice. 3. Unchoose: Revert the choice you made in step 1 (remove the item) to reset the state cleanly for the next iteration of the loop.

How does Backtracking differ from pure Depth-First Search (DFS)?

Backtracking is a highly specific, optimized form of DFS. Pure DFS traverses every single node in a tree blindly. Backtracking actively evaluates the current state, and if it violates problem constraints, it 'prunes' the branch, stopping the DFS instantly and retreating up the tree.

Real-World Example

Route Optimization and Logistics. If a delivery driver has 10 packages, an algorithm must find the shortest possible route connecting all 10 houses (a variation of the Traveling Salesperson Problem). Backtracking generates routes: House A -> House B -> House C. If the distance suddenly exceeds a known 'best route', the algorithm backtracks immediately, ignoring the millions of possible routes that branch off that terrible start.

example
java
import java.util.*;

public class RouteOptimizer {
    int shortestDistance = Integer.MAX_VALUE;
    List<String> bestRoute = new ArrayList<>();

    public void findBestRoute(List<String> currentRoute, int currentDistance, List<String> unvisited) {
        // Base Case: All stops visited
        if (unvisited.isEmpty()) {
            if (currentDistance < shortestDistance) {
                shortestDistance = currentDistance;
                bestRoute = new ArrayList<>(currentRoute);
            }
            return;
        }
        
        for (int i = 0; i < unvisited.size(); i++) {
            String nextStop = unvisited.get(i);
            int distanceToNext = calculateDistance(currentRoute.get(currentRoute.size() - 1), nextStop);
            
            // PRUNING: If this path is already longer than our best, stop exploring it entirely!
            if (currentDistance + distanceToNext >= shortestDistance) continue;
            
            // Choose
            currentRoute.add(nextStop);
            unvisited.remove(i);
            
            // Explore
            findBestRoute(currentRoute, currentDistance + distanceToNext, unvisited);
            
            // Unchoose (Backtrack)
            unvisited.add(i, nextStop);
            currentRoute.remove(currentRoute.size() - 1);
        }
    }
    
    private int calculateDistance(String a, String b) { return 10; /* Mock logic */ }
}

Check Your Knowledge

Test your understanding of Backtracking with these quick questions.

Question 1

What is the crucial final step of a backtracking loop that differentiates it from standard recursion?

Question 2

Why is 'Pruning' fundamentally important in backtracking algorithms?

Question 3

When adding a valid combination to a master `results` list in Java, what must you do to prevent data loss?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A