AlgoTales · Roadmap

Generate permutations

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A permutation is one ordering of a set of items, and generating permutations means listing every different order. You pick the first item, then the second from what is left, and so on. It is how you try "every possible sequence" when order matters.

Practical use cases

  • Web app: Delivery stop order for a rider. A food-delivery dashboard has 4 orders to hand to one rider, and the dispatcher wants the cheapest order of stops. Trying every ordering of 4 stops gives 24 routes, so the app can calculate the distance of each and show the shortest. For small batches this simple approach is perfectly fine and easy to trust.
  • Web app: Interview panel orders. A college portal needs to show an admin every way three interviewers can be ordered on a panel, so conflicts with their calendars can be checked. The code picks one interviewer for slot one, one of the remaining for slot two, and so on. All 6 orders appear exactly once. The admin can trust the list is complete and check each order against the calendars.
  • System: Password guessing and game AI. Security testing tools try every ordering of a few known words to see whether a password could be guessed. Game AI tries every order of moves for a short plan. Both rely on listing each ordering exactly once. Nothing is missed and nothing is tried twice, which keeps these searches fast for small groups.

The story: Who Sits Where at the Wedding

Zoya's cousin was getting married, and Zoya was in charge of the photo bench: three seats, three relatives, Grandpa Bhaskar, Aunty and Uncle. "Who sits where matters!" fussed Aunty. "Nobody wants to be at the edge in every photo." So Zoya decided to take one photo of every possible seating order.

She started badly: she shuffled people randomly, and soon she was not sure which orders she had already shot. Mira, on duty with the sweets, offered a plan: "Fill the seats left to right. For each seat, pick someone who has not sat yet."

Seat 1: Grandpa. Seat 2: Aunty. Seat 3: Uncle. Click! Then Mira said, "Now stand up the last person and see who else could take seat 3." Nobody else was free, so she stood up the second person too, and tried Uncle in seat 2, leaving Aunty for seat 3. Click!

Six clicks later, Grandpa had been first twice, Aunty twice and Uncle twice. Not a single order was missing or repeated. That is backtracking for permutations: one person picked per seat, with a "used" tick so nobody sits twice.

How to spot this problem, and where you need it

You need to try every possible order of a small group of items, because the result depends on which comes first, and you do not want to miss any or repeat any.

Signs you need it

  • The problem says "all arrangements", "all orderings" or "every possible sequence", and swapping two items gives a different answer.
  • You find yourself writing three or four nested loops, each skipping the items already used by the earlier loops.
  • You are scheduling, routing or seating a small number of things and the cost depends on their order.

Where to use it in a project

  • Brute-force checking of delivery stop orders, task orders or interview panel orders when the group is small, say up to 8 or 9 items.
  • Generating test data in all different orders to see if a form or API behaves the same regardless of field order.

The solution

Keep a list of what you have placed so far and a note of which items are already used. Pick any unused item, place it, and repeat for the next position. When every position is filled, you have one complete ordering, so record it. Then undo the last placement and try the next unused item instead. That undo-and-retry step is backtracking, and it visits every ordering exactly once without needing a loop per position.

Payoff: Before: nested loops that only handle exactly 3 items and miss cases. After: one function listing all 24 orders of 4 stops, all 720 for 6 stops, with no duplicates.

Explain it like I am 8

Line up three toy cars in a row. Now find every different order you can put them in. A trick: choose the first car, then the second from the cars left, then the last. When you finish a row, take the last cars back and try another one in that spot.

How it works, step by step

  1. Keep a path (the order built so far) and a used mark for every item.
  2. Base case: when the path has as many items as the list, save a copy of it.
  3. Loop over all items. Skip any that are already used.
  4. Choose: mark it used and add it to the path, then explore the next seat.
  5. Un-choose: remove it from the path and clear its used mark, so the next seat can try it.

The code in four languages

PHP

<?php
// All orderings of the items. $used stops us from using one item twice.
function permutations(array $items): array {
    $result = [];
    $path = [];
    $used = array_fill(0, count($items), false);
    $explore = function () use (&$explore, &$result, &$path, &$used, $items) {
        if (count($path) === count($items)) {
            $result[] = $path;                 // base case: every seat is filled
            return;
        }
        foreach ($items as $i => $item) {
            if ($used[$i]) continue;           // already seated
            $used[$i] = true;                  // choose
            $path[] = $item;
            $explore();                        // explore the next seat
            array_pop($path);                  // un-choose
            $used[$i] = false;
        }
    };
    $explore();
    return $result;
}

foreach (permutations([1, 2, 3]) as $p) {
    echo '[' . implode(', ', $p) . "]\n";
}

JavaScript

// All orderings of the items. used[] stops us from using one item twice.
function permutations(items) {
  const result = [];
  const path = [];
  const used = new Array(items.length).fill(false);
  function explore() {
    if (path.length === items.length) {
      result.push([...path]);          // base case: every seat is filled
      return;
    }
    for (let i = 0; i < items.length; i++) {
      if (used[i]) continue;           // already seated
      used[i] = true;                  // choose
      path.push(items[i]);
      explore();                       // explore the next seat
      path.pop();                      // un-choose
      used[i] = false;
    }
  }
  explore();
  return result;
}

for (const p of permutations([1, 2, 3])) {
  console.log('[' + p.join(', ') + ']');
}

Java

import java.util.*;

public class Main {
    // All orderings of the items. used[] stops us from using one item twice.
    static List<List<Integer>> permutations(int[] items) {
        List<List<Integer>> result = new ArrayList<>();
        explore(items, new boolean[items.length], new ArrayList<>(), result);
        return result;
    }

    static void explore(int[] items, boolean[] used, List<Integer> path, List<List<Integer>> result) {
        if (path.size() == items.length) {
            result.add(new ArrayList<>(path));      // base case: every seat is filled
            return;
        }
        for (int i = 0; i < items.length; i++) {
            if (used[i]) continue;                  // already seated
            used[i] = true;                         // choose
            path.add(items[i]);
            explore(items, used, path, result);     // explore the next seat
            path.remove(path.size() - 1);           // un-choose
            used[i] = false;
        }
    }

    public static void main(String[] args) {
        for (List<Integer> p : permutations(new int[]{1, 2, 3})) {
            System.out.println(p);                  // e.g. [1, 2, 3]
        }
    }
}

Go

package main

import "fmt"

// permutations returns all orderings of the items. used[] stops us from using one item twice.
func permutations(items []int) [][]int {
	var result [][]int
	var path []int
	used := make([]bool, len(items))
	var explore func()
	explore = func() {
		if len(path) == len(items) {
			result = append(result, append([]int(nil), path...)) // base case: every seat is filled
			return
		}
		for i, item := range items {
			if used[i] { // already seated
				continue
			}
			used[i] = true // choose
			path = append(path, item)
			explore()                 // explore the next seat
			path = path[:len(path)-1] // un-choose
			used[i] = false
		}
	}
	explore()
	return result
}

func main() {
	for _, p := range permutations([]int{1, 2, 3}) {
		fmt.Println(p) // e.g. [1 2 3]
	}
}

Time: O(n × n!) · Extra space: O(n). There are n! orders, which grows scarily fast (10 items already give 3.6 million). Copying each costs n.

Watch out for

  • Forgetting to clear used[i] when backing up, so later branches think the item is still seated.
  • Saving the live path instead of a copy of it.
  • With repeated items (like 1, 1, 2) this version lists the same order twice. You need to skip equal neighbours in a sorted list to avoid that.

Quick check

  1. How many permutations do 4 different items have?
    • 8
    • 12
    • 16
    • 24
  2. What does the used[] array prevent?
    • Using the same item twice in one arrangement
    • Sorting the output
    • Stack overflow
  3. Subsets vs permutations: which cares about order?
    • Subsets
    • Both equally
    • Neither
    • Permutations