Bird
Raised Fist0
Interview PrepbacktrackingmediumAmazonGoogleMicrosoft

Permutations II (With Duplicates)

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize and Sort Input

The input array [1,1,2] is sorted to group duplicates together, resulting in [1,1,2]. This sorting is essential for the skip condition to work correctly.

💡 Sorting groups duplicates so the algorithm can easily detect and skip repeated elements at each recursion level.
Line:nums.sort()
💡 Sorting is a prerequisite that enables efficient duplicate skipping during backtracking.
📊
Permutations II (With Duplicates) - Watch the Algorithm Execute, Step by Step
Watching this step-by-step execution reveals how sorting and skipping duplicates at each recursion level efficiently prune redundant branches, which is hard to grasp from code alone.
Step 1/15
·Active fill★Answer cell
enteringnums=[1,1,2]start=0
Call Path (current → root)
backtrack(start=0)
choosingnums=[1,1,2]start=0
Call Path (current → root)
backtrack(start=0)
Tried
i=0
Remaining
i=1i=2
Partial: [1]
choosingnums=[1,1,2]start=1
Call Path (current → root)
backtrack(start=1)
backtrack(start=0)
Remaining
i=1i=2
Partial: [1]
choosingnums=[1,1,2]start=2
Call Path (current → root)
backtrack(start=2)
backtrack(start=1)
backtrack(start=0)
Remaining
i=2
Partial: [1, 1]
choosingnums=[1,1,2]start=2
Call Path (current → root)
backtrack(start=2)
backtrack(start=1)
backtrack(start=0)
Tried
i=2
Partial: [1, 1, 2]
choosingnums=[1,1,2]start=2
Call Path (current → root)
backtrack(start=2)
backtrack(start=1)
backtrack(start=0)
Tried
i=2
Partial: [1, 1]
Found 1: [1,1,2]
choosingnums=[1,2,1]start=1
Call Path (current → root)
backtrack(start=1)
backtrack(start=0)
Tried
i=1i=2
Partial: [1, 2]
Found 1: [1,1,2]
choosingnums=[1,2,1]start=2
Call Path (current → root)
backtrack(start=2)
backtrack(start=1)
backtrack(start=0)
Tried
i=2
Partial: [1, 2, 1]
Found 1: [1,1,2]
choosingnums=[1,2,1]start=2
Call Path (current → root)
backtrack(start=2)
backtrack(start=1)
backtrack(start=0)
Tried
i=2
Partial: [1, 2]
Found 2: [1,1,2] [1,2,1]
choosingnums=[1,1,2]start=0
Call Path (current → root)
backtrack(start=0)
Tried
i=0
Remaining
i=2
✂ nums[1]=1 already fixed at this level
Found 2: [1,1,2] [1,2,1]
enteringnums=[2,1,1]start=1
Call Path (current → root)
backtrack(start=1)
backtrack(start=0)
Tried
i=0i=2
Partial: [2]
Found 2: [1,1,2] [1,2,1]
choosingnums=[2,1,1]start=1
Call Path (current → root)
backtrack(start=1)
backtrack(start=0)
Tried
i=1
Remaining
i=2
Partial: [2, 1]
Found 2: [1,1,2] [1,2,1]
choosingnums=[2,1,1]start=2
Call Path (current → root)
backtrack(start=2)
backtrack(start=1)
backtrack(start=0)
Tried
i=2
Partial: [2, 1, 1]
Found 2: [1,1,2] [1,2,1]
backtrackingnums=[2,1,1]start=1
Call Path (current → root)
backtrack(start=0)
Tried
i=0i=2
Found 3: [1,2,1] [2,1,1]
backtrackingnums=[1,1,2]start=0
Call Path (current → root)
root call
Tried
i=0i=2
Found 3: [1,2,1] [2,1,1]

Key Takeaways

✓ Sorting the input array is crucial to group duplicates and enable efficient skipping of repeated elements at each recursion level.

Without sorting, detecting duplicates to prune branches would be much harder and less efficient.

✓ The 'seen' set at each recursion level tracks which elements have been fixed at that position, preventing duplicate permutations by skipping repeated elements.

This local duplicate tracking is the key insight that avoids generating redundant permutations.

✓ Backtracking with swapping and undoing swaps restores the array state after exploring each branch, allowing the algorithm to systematically explore all unique permutations.

Understanding how backtracking restores state is essential to grasp how the recursion tree is fully explored without side effects.

Practice

(1/5)
1. You are given a string containing parentheses and letters. The goal is to remove the minimum number of parentheses to make the string valid (balanced parentheses) and return all possible results. Which algorithmic approach guarantees finding all valid strings with the minimum removals efficiently?
easy
A. Greedy approach that removes invalid parentheses from left to right without backtracking
B. Dynamic Programming that counts valid substrings and reconstructs solutions
C. Breadth-First Search (BFS) that explores all strings by removing one parenthesis at a time level-by-level
D. Brute force generating all subsequences and checking validity

Solution

  1. Step 1: Understand problem constraints

    The problem requires minimal removals and all valid results, so partial or greedy removal may miss some minimal solutions.
  2. Step 2: Analyze BFS approach

    BFS explores all strings by removing one parenthesis at a time, level-by-level, ensuring the first valid strings found have minimal removals and all such strings are collected.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    BFS guarantees minimal removals and completeness [OK]
Hint: Minimal removals require level-by-level BFS [OK]
Common Mistakes:
  • Greedy misses some minimal solutions
  • Brute force is correct but inefficient
  • DP doesn't apply directly here
2. What is the time complexity of the bitmask-optimized backtracking solution for the N-Queens problem, and why is the common misconception that it is O(n^3) incorrect?
medium
A. O(n^3) because there are three nested loops over rows, columns, and diagonals
B. O(2^n) because bitmasking iterates over all subsets of columns
C. O(n!) because each row places one queen and pruning reduces the search space factorially
D. O(n^2) because each queen placement checks all previous rows and columns

Solution

  1. Step 1: Identify the branching factor per row

    Each row places exactly one queen, and pruning avoids invalid columns and diagonals, reducing choices drastically.
  2. Step 2: Understand factorial growth

    Because queens cannot share columns, the number of ways to place queens is at most n!; pruning reduces this further but worst-case remains O(n!).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Bitmask pruning reduces search to permutations of columns [OK]
Hint: N-Queens search space is permutations, not polynomial loops [OK]
Common Mistakes:
  • Assuming nested loops imply cubic time
  • Confusing bitmask subsets with full subsets
  • Ignoring pruning effect
3. Examine the following code snippet for the Word Search problem. It is almost correct but contains one subtle bug. Identify the line causing the bug.
medium
A. Line where board[r][c] = temp is restored after recursion
B. Line where temp = board[r][c]
C. Line where directions are defined
D. Line missing board[r][c] = '#' to mark visited

Solution

  1. Step 1: Identify missing visited marking

    The code does not mark the current cell as visited before recursive calls, allowing revisits.
  2. Step 2: Understand impact of missing marking

    Without marking, dfs can revisit the same cell multiple times, causing incorrect matches or infinite loops.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Marking visited cells is essential to prevent reuse [OK]
Hint: Check if visited cells are marked before recursion [OK]
Common Mistakes:
  • Forgetting to mark visited cells
  • Restoring cell too early
4. Suppose the problem is modified so that digits can be repeated any number of times (reuse allowed), and you want to generate all letter combinations of length n from the given digits. Which modification to the algorithm correctly handles this reuse scenario?
hard
A. Modify backtracking to allow choosing the same digit multiple times by not incrementing the index after each choice until length n is reached
B. Sort digits and generate combinations by picking letters only once per digit
C. Use dynamic programming to store combinations of length k and build up to length n without reuse
D. Use the same iterative queue approach but do not advance the digit index; instead, for each combination, append letters from all digits repeatedly until length n is reached

Solution

  1. Step 1: Understand reuse requirement

    Allowing reuse means digits can be chosen multiple times to build combinations of length n.
  2. Step 2: Identify correct approach

    Backtracking can be modified to not increment the digit index after choosing a letter, allowing reuse until length n is reached.
  3. Step 3: Why other options fail

    Iterative queue approach as-is assumes fixed digit positions; DP without reuse does not handle repeated digits; sorting and picking once per digit ignores reuse.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Backtracking with flexible index handles reuse elegantly [OK]
Hint: Backtracking index controls reuse by not advancing [OK]
Common Mistakes:
  • Trying to reuse digits in iterative approach without index control
  • Ignoring reuse in DP or sorting
5. Suppose the problem is modified so that IP address segments can be reused multiple times (i.e., segments can overlap and be repeated). Which modification to the backtracking algorithm correctly handles this variant without generating duplicates or invalid IPs?
hard
A. Remove the pruning condition on remaining characters and segments to allow overlapping segments
B. Use a memoization cache keyed by (start, segments formed) to avoid recomputing paths
C. Allow segments to be reused by resetting start index to previous segment start after each addition
D. Change the algorithm to generate all permutations of segments without pruning

Solution

  1. Step 1: Understand reuse implies overlapping segments

    Allowing reuse means the same substring can be used multiple times, potentially causing repeated computations.
  2. Step 2: Apply memoization to avoid duplicates

    Memoization keyed by (start, segments formed) prevents recomputing the same subproblems and avoids duplicates.
  3. Step 3: Evaluate other options

    Removing pruning causes inefficiency; resetting start index breaks segment order; generating all permutations ignores validity and pruning.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Memoization efficiently handles reuse without duplicates [OK]
Hint: Memoization avoids recomputation when segments can be reused [OK]
Common Mistakes:
  • Removing pruning causes timeouts
  • Resetting start index breaks segment order
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