↓Skip to main content
  1. LeetCode/

LeetCode 46: Permutations

·2 mins· ·
LeetCode Medium Array Backtracking
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-21

  • Submissions: Accepted → Memory Limit Exceeded → Runtime Error → Wrong Answer → Accepted ×2 → Wrong Answer → Runtime Error → Accepted → Runtime Error → Wrong Answer → Accepted

Approach
#

Permutations depend on order, so each level may pick any unused number (Backtracking template). Mark it in used[i], checking before choosing and clearing on backtrack. Record a copy when path has length n.

My Attempts
#

This took 12 submissions; the first passed (filtering out numbers equal to the current one), and each rewrite then slipped on details:

  • An unclosed parenthesis, and putting the index i rather than the value nums[i] into the answer ([3] returned [[0]]).
  • Forgetting to call dfs or to return, and wrapping the answer in an extra list ([[[3]]]).

Solution
#

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res, path = [], []
        used = [False] * len(nums)
        def dfs():
            if len(path) == len(nums):
                res.append(path[:])
                return
            for i, x in enumerate(nums):
                if used[i]:
                    continue
                used[i] = True
                path.append(x)
                dfs()
                path.pop()
                used[i] = False
        dfs()
        return res

Complexity
#

Time O(n · n!), space O(n) excluding output.

Mistakes to Avoid
#

  • Put the value nums[i] into path, not the index i.
  • Filtering used values by j != i works only without duplicates; marking indices is safer.

Interview Explanation
#

Order matters, so each level may pick any unused number; I mark it in a used array, recurse, unmark, and record a copy when the path is full. Time O(n · n!).

Related

LeetCode 39: Combination Sum
·2 mins
LeetCode Medium Array Backtracking
LeetCode 39 note: numbers may be reused, so the next level starts at i (not i + 1), which also avoids duplicates differing only in order
LeetCode 40: Combination Sum II
·2 mins
LeetCode Medium Array Backtracking
LeetCode 40 note: each number is used once and duplicates exist, so sort, start the next level at i + 1, and skip equal values within a level
LeetCode 31: Next Permutation
·2 mins
LeetCode Medium Array Two-Pointers
LeetCode 31 note: from the right find the first dip i, swap it with the smallest larger value to its right, then reverse everything after i, with comparisons that include equality
LeetCode 33: Search in Rotated Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 33 note: after rotation one side of mid is always sorted; check whether the target lies in it and search there, otherwise search the other side
LeetCode 34: Find First and Last Position of Element in Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 34 note: two lower bounds: the first position >= target, and the first position >= target + 1 minus one
LeetCode 36: Valid Sudoku
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 note: each digit may appear once per row, column and 3 × 3 box; put (digit, row), (digit, column) and (digit, box) keys into one set