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
Coders Crushby Napplied AI

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

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • AI Discovery

Coders Crush by Napplied AI - Built for engineers preparing for FAANG/MAANG interviews

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

Backtracking: build permutation by adding unused elements one by one, backtrack after exploring each choice.

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
Time:O(n! * 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
GoogleAmazonMetaMicrosoftApple