← L&T Mindtree bank

L&T Mindtree · Question 38 · Backtracking

Permutations

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

Problem

You are given an array of distinct integers. Return all possible permutations.

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 = [0, 1]
Output:
[[0, 1], [1, 0]]

Constraints

Distinct values; 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>> result= new ArrayList<>()backtrack(nums, 0, result)RETURN resultDEFINE static voidbacktrack(int[] nums, intstart, List<List<Integer>…if (start ==nums.length)List<Integer> cur = newArrayList<>()for (int v : nums)cur.add(v)result.add(cur)RETURNfor (int i = start; i< nums.length; i++)swap(nums, start, i)backtrack(nums, start + 1,result)swap(nums, start, i)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[]{0, 1}))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