← Deloitte bank

Deloitte · Question 37 · Backtracking

Permutation (all permutations)

BacktrackingJavacode⏱ O(n*n!)💾 O(n)
Service-based

Problem

Generate all permutations of distinct numbers via backtracking.

Approach

Swap each position with every later choice, recursing and swapping back.

Time O(n*n!)Space O(n)

How it works

  1. 1Fix each index with every remaining choice.
  2. 2Swap back to restore state.

Sample input / output

Input:
nums = [1, 2, 3]
Output:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

Constraints

Distinct numbers; 1 <= length <= 6.

Solution — read it, then walk it

Time O(n*n!)Space O(n)Loops 2Branches 1Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE staticList<List<Integer>>permute(int[] nums)List<List<Integer>> res =new ArrayList<>()back(nums, 0, res)RETURN resDEFINE static voidback(int[] a, int idx,List<List<Integer>> res)if (idx == a.length)List<Integer> cur = newArrayList<>()for (int v : a)cur.add(v)res.add(cur)RETURNfor (int i = idx; i <a.length; i++)swap(a, i, idx)back(a, idx + 1, res)swap(a, i, idx)DEFINE static voidswap(int[] a, int i, int j)DEFINE t = a[i]a[i] = a[j]a[j] = tDEFINE static voidmain(String[] args)System.out.println(permute(newint[]{1, 2, 3}))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits