Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

Generate All Permutations of Array in DSA Typescript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Generate All Permutations of Array
Start with empty permutation
↓
Choose element not in current permutation
↓
Add element to current permutation
↓
Is permutation complete?
No→Repeat choosing next element
Yes↓
Save current permutation
↓
Backtrack: Remove last element
↩Back to choosing element
Build permutations by adding unused elements one by one, save when full length reached, then backtrack to try other options.
Execution Sample
DSA Typescript
function permute(arr: number[]): number[][] {
  const result: number[][] = [];
  const backtrack = (temp: number[]) => {
    if (temp.length === arr.length) result.push([...temp]);
    else {
      for (const num of arr) {
        if (!temp.includes(num)) {
          temp.push(num);
          backtrack(temp);
          temp.pop();
        }
      }
    }
  };
  backtrack([]);
  return result;
}
Recursively build permutations by adding unused elements until full length, then save and backtrack.
Execution Table
StepOperationCurrent PermutationActionVisual State
1Start backtrack with [][]Choose element 1[1]
2Add 1[1]Choose element 2[1,2]
3Add 2[1,2]Choose element 3[1,2,3]
4Add 3[1,2,3]Permutation complete, save[1,2,3]
5Backtrack[1,2,3]Remove 3[1,2]
6Backtrack[1,2]Remove 2[1]
7Choose element 3[1]Add 3[1,3]
8Add 3[1,3]Choose element 2[1,3,2]
9Add 2[1,3,2]Permutation complete, save[1,3,2]
10Backtrack[1,3,2]Remove 2[1,3]
11Backtrack[1,3]Remove 3[1]
12Backtrack[1]Remove 1[]
13Choose element 2[]Add 2[2]
14Add 2[2]Choose element 1[2,1]
15Add 1[2,1]Choose element 3[2,1,3]
16Add 3[2,1,3]Permutation complete, save[2,1,3]
17Backtrack[2,1,3]Remove 3[2,1]
18Backtrack[2,1]Remove 1[2]
19Choose element 3[2]Add 3[2,3]
20Add 3[2,3]Choose element 1[2,3,1]
21Add 1[2,3,1]Permutation complete, save[2,3,1]
22Backtrack[2,3,1]Remove 1[2,3]
23Backtrack[2,3]Remove 3[2]
24Backtrack[2]Remove 2[]
25Choose element 3[]Add 3[3]
26Add 3[3]Choose element 1[3,1]
27Add 1[3,1]Choose element 2[3,1,2]
28Add 2[3,1,2]Permutation complete, save[3,1,2]
29Backtrack[3,1,2]Remove 2[3,1]
30Backtrack[3,1]Remove 1[3]
31Choose element 2[3]Add 2[3,2]
32Add 2[3,2]Choose element 1[3,2,1]
33Add 1[3,2,1]Permutation complete, save[3,2,1]
34Backtrack[3,2,1]Remove 1[3,2]
35Backtrack[3,2]Remove 2[3]
36Backtrack[3]Remove 3[]
37All permutations generated[]EndAll permutations saved
💡 All elements tried at all positions; recursion ends when all permutations saved.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 12After Step 25Final
current permutation (temp)[][1][1,2,3][][3][]
result (saved permutations)[][][[1,2,3]][[1,2,3],[1,3,2]][[1,2,3],[1,3,2],[2,1,3],[2,3,1]][[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Key Moments - 3 Insights
Why do we need to remove the last element after recursive call (backtrack)?
Removing the last element after recursion lets us try other elements in that position. See steps 4 and 5 where 3 is removed to try other options.
Why do we check if element is already in current permutation before adding?
To avoid duplicates in the permutation. The check prevents adding the same element twice, e.g., skips 1 and 2 when current is [1,2].
When do we know a permutation is complete?
When the current permutation length equals the original array length, like in step 4 where length 3 means complete permutation saved.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 4. What is the current permutation?
A[1,2]
B[1,2,3]
C[1,3]
D[]
💡 Hint
Check the 'Current Permutation' column at step 4 in the execution_table.
At which step does the algorithm backtrack after saving the permutation [2,3,1]?
AStep 23
BStep 21
CStep 22
DStep 24
💡 Hint
Look for 'Permutation complete, save' with [2,3,1] and then the next step showing 'Remove 1'.
If we remove the check for element already in permutation, what happens?
APermutations will have duplicates of same element
BAlgorithm will run faster
CNo permutations will be generated
DAlgorithm will crash
💡 Hint
Refer to key_moments about why we check if element is already in current permutation.
Concept Snapshot
Generate all permutations by:
- Recursively adding unused elements to current list
- When length equals input array, save permutation
- Backtrack by removing last element to try others
- Use check to avoid duplicates
- Result is all possible orderings
Full Transcript
This concept shows how to generate all permutations of an array by building them step-by-step. We start with an empty list and add elements one by one if they are not already used. When the current list length matches the original array length, we save that permutation. Then we remove the last element to try other possibilities, called backtracking. This process repeats until all permutations are found. The execution table traces each step, showing how the current permutation grows and shrinks, and when permutations are saved. Key moments explain why we remove elements after recursion and why we check for duplicates. The visual quiz tests understanding of these steps and effects of changes.

Practice

(1/5)
1. What does the process of generating all permutations of an array mean?
easy
A. Listing all possible orders of the array elements
B. Sorting the array in ascending order
C. Removing duplicate elements from the array
D. Finding the largest element in the array

Solution

  1. Step 1: Understand permutations

    Permutations are all possible ways to arrange elements in order.
  2. Step 2: Apply to array

    Generating all permutations means listing every possible order of the array elements.
  3. Final Answer:

    Listing all possible orders of the array elements -> Option A
  4. Quick Check:

    Permutations = all orders [OK]
Hint: Permutations = all ways to arrange elements [OK]
Common Mistakes:
  • Confusing permutations with sorting
  • Thinking permutations remove duplicates
  • Mixing permutations with finding max element
2. Which of the following TypeScript function signatures correctly represents a function that generates all permutations of an array of numbers?
easy
A. function permute(arr: number[][]): number[]
B. function permute(arr: number): number[]
C. function permute(arr: number[]): number[][]
D. function permute(arr: string[]): string

Solution

  1. Step 1: Analyze input and output types

    The input is an array of numbers, so type is number[]. The output is all permutations, which is an array of arrays of numbers, so number[][].
  2. Step 2: Match function signature

    function permute(arr: number[]): number[][] matches input number[] and output number[][] correctly.
  3. Final Answer:

    function permute(arr: number[]): number[][] -> Option C
  4. Quick Check:

    Input array, output array of arrays [OK]
Hint: Input array, output array of arrays for permutations [OK]
Common Mistakes:
  • Using single number instead of array as input
  • Returning a single array instead of array of arrays
  • Mixing string and number types incorrectly
3. What is the output of the following TypeScript code?
function permute(arr: number[]): number[][] {
  if (arr.length === 0) return [[]];
  const result: number[][] = [];
  for (let i = 0; i < arr.length; i++) {
    const rest = [...arr.slice(0, i), ...arr.slice(i + 1)];
    for (const perm of permute(rest)) {
      result.push([arr[i], ...perm]);
    }
  }
  return result;
}

console.log(permute([1, 2]));
medium
A. [[1, 2], [2, 1]]
B. [[1, 2]]
C. [[2, 1]]
D. []

Solution

  1. Step 1: Understand base case and recursion

    Base case returns [[]] for empty array. For [1,2], it picks each element and permutes the rest.
  2. Step 2: Trace recursive calls for [1,2]

    First i=0: arr[i]=1, rest=[2], permute([2]) returns [[2]], so push [1,2]. Then i=1: arr[i]=2, rest=[1], permute([1]) returns [[1]], so push [2,1].
  3. Final Answer:

    [[1, 2], [2, 1]] -> Option A
  4. Quick Check:

    Permutations of [1,2] = [[1,2],[2,1]] [OK]
Hint: Check base case and recursive build-up [OK]
Common Mistakes:
  • Forgetting to include all permutations
  • Returning only one permutation
  • Confusing order of elements
4. Identify the error in this TypeScript function that attempts to generate all permutations of an array:
function permute(arr: number[]): number[][] {
  if (arr.length === 1) return [arr];
  const result: number[][] = [];
  for (let i = 0; i < arr.length; i++) {
    const rest = arr.slice(1);
    for (const perm of permute(rest)) {
      result.push([arr[i], ...perm]);
    }
  }
  return result;
}
medium
A. The base case should return an empty array
B. The function should return a flat array, not nested arrays
C. The loop should start from 1 instead of 0
D. The slice should exclude the current element, not always the first

Solution

  1. Step 1: Analyze the slice operation

    The code uses arr.slice(1) always, which removes only the first element, not the current element at index i.
  2. Step 2: Correct slice to exclude current element

    To generate permutations correctly, slice should exclude arr[i], e.g., [...arr.slice(0, i), ...arr.slice(i + 1)].
  3. Final Answer:

    The slice should exclude the current element, not always the first -> Option D
  4. Quick Check:

    Exclude current element in slice [OK]
Hint: Slice must exclude current index element [OK]
Common Mistakes:
  • Always slicing from index 1 ignoring i
  • Wrong base case length check
  • Returning wrong data structure
5. Given an array with possible duplicate elements, how can you modify the permutation generation function to avoid duplicate permutations?
function permuteUnique(arr: number[]): number[][] {
  // Your code here
}
hard
A. Use a Set to store all permutations after generation
B. Sort the array first and skip duplicates during recursion
C. Remove duplicates from the array before generating permutations
D. Generate permutations normally without any change

Solution

  1. Step 1: Understand duplicate permutations problem

    Duplicates in input cause repeated permutations if not handled.
  2. Step 2: Sort and skip duplicates during recursion

    Sorting helps group duplicates. During recursion, skip elements equal to previous to avoid repeated branches.
  3. Step 3: Why other options fail

    Using Set after generation is costly. Removing duplicates loses valid permutations. No change causes duplicates.
  4. Final Answer:

    Sort the array first and skip duplicates during recursion -> Option B
  5. Quick Check:

    Sort + skip duplicates = unique permutations [OK]
Hint: Sort array and skip duplicates in recursion [OK]
Common Mistakes:
  • Removing duplicates from input loses valid permutations
  • Using Set after generation wastes time and memory
  • Ignoring duplicates causes repeated permutations
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard