Coders Crushby Napplied AI
Back to DSA Problems
MediumLeetCode #46Backtracking

Permutations

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Constraints
1 <= nums.length <= 6, -10 <= nums[i] <= 10, All integers of nums are unique
Examples
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Solution Approach

Recursively explore all possible solutions. Make choice, explore recursively, undo choice (backtrack). Use when searching permutations, combinations, or paths.

Implementation
def permute(nums):
    result = []
    def backtrack(path, remaining):
        if not remaining:
            result.append(path)
            return
        for i in range(len(remaining)):
            backtrack(path + [remaining[i]], remaining[:i] + remaining[i+1:])
    backtrack([], nums)
    return result
Complexity Analysis

Time Complexity

O(n!)

Space Complexity

O(n)
Key Learning Points
Recursive explorationUndo/backtrack stepUseful for all permutations/combinations
Related Problems to Practice
PermutationsCombinationsN-QueensWord Search
Complexity
Time:O(n!)
Space:O(n)
Hints
  • 1.Each position can be filled by any remaining element
  • 2.Backtrack after trying each choice
  • 3.n! total permutations
Asked at
Google
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless

Amazon
Meta
Microsoft
Apple