AlgoInsight

DSA problem

Generate All Permutations of a String

MediumRecursionPattern: BacktrackingbeginnerFree

Given a string S, generate all possible permutations of its characters and return them.

This is a classic backtracking problem and one of the most important recursion exercises. The idea: fix one character at a time, then recursively permute the remaining characters. For a string of length N there are N! permutations. At each level of recursion you try placing each remaining character at the current position; after exploring that branch you backtrack - undo the choice and try the next character.

This generate-explore-undo pattern is the essence of backtracking, used to solve Sudoku, N-Queens, combinatorial optimization, constraint satisfaction, and many graph problems. Handling duplicates (e.g. "aab" should not produce repeated permutations) is a common follow-up - use a set at each recursion level to skip characters already placed at that position.

Examples

Example 1
Input: S = "ABC"
Output: ["ABC", "ACB", "BAC", "BCA", "CBA", "CAB"]
Explanation: 3! = 6 permutations. Swapping the fixed position with each candidate character (A, then B, then C) produces this order.
Example 2
Input: S = "A"
Output: ["A"]
Explanation: A single character has exactly one permutation.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

recursionbacktrackingstring

Browse all DSA problems