Relay Practice Lineups

EasybacktrackingAlso known as Permutations

A swim coach has a freestyle relay team. Each swimmer swims exactly one leg, one after another, and the coach suspects the order matters: a fast starter, a steady middle, a strong finisher. So over the season the team will time every possible order once.

The coach needs the complete list of lineups to pin on the board, with no lineup missing and none listed twice.

Your task

Write allLineups(swimmers). swimmers is a list of different names. Return every possible lineup: a list that contains each swimmer exactly once, in the order they swim.

The lineups can be returned in any order, but the order of names inside a lineup is the swim order, so it matters. An empty team has exactly one lineup, the empty one: return [[]].

allLineups(swimmers: string[]) → string[][] Any order of the returned list is accepted.

Examples

Example 1
Input
swimmers = ["Ana", "Ben", "Cy"]
Output
[["Ana", "Ben", "Cy"], ["Ana", "Cy", "Ben"], ["Ben", "Ana", "Cy"], ["Ben", "Cy", "Ana"], ["Cy", "Ana", "Ben"], ["Cy", "Ben", "Ana"]]
Why

3 choices for the first leg, then 2 for the second, then the last swimmer is fixed: 3 × 2 × 1 = 6 lineups. Ana-Ben-Cy and Ben-Ana-Cy are different lineups, because the first leg is swum by someone else.

Example 2
Input
swimmers = ["Mo"]
Output
[["Mo"]]
Why

One swimmer, one lineup.

Constraints

  • 0 ≤ swimmers.length ≤ 6
  • All names are different, non-empty strings.
  • Lineups may be returned in any order.
Start with brute force

Generate every sequence of n names where each leg may be anyone, including repeats, and keep only the ones without a repeated name. That is nⁿ sequences to make the n! valid ones: 46,656 for 6 swimmers to find 720 lineups, and 10 billion for 10 swimmers to find 3.6 million.

The waste comes from noticing a repeat only at the end. If Ana is already in the lineup, every sequence that picks Ana again is dead from that moment, so do not build it at all.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code