</>

46. Permutations

Medium NeetCode 150
Backtracking Time O(N!) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Backtracking
Time
O(N!)
Space
O(N)

Standard Solution (C++)

SummaryGiven a list of distinct integers, generate and return all possible orderings (permutations) of those integers in any order.

Approach
  • Use backtracking with in-place swapping: at each position idx, try placing every remaining element there by swapping it into idx, recurse on the tail, then swap back to restore state.
  • When idx reaches the last position, the entire array is one complete permutation — record it.
  • This avoids extra visited arrays or copies: the array itself encodes "which elements are still available" via the unvisited suffix [idx, n).
  • Produces exactly n! permutations, each built in O(n) time for the final copy.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
    void backtrack(vector<int>& nums, int start, vector<vector<int>>& result) {
        // All positions filled — record this permutation
        if (start == (int)nums.size()) {
            result.push_back(nums);
            return;
        }
        // Try placing each remaining element at position `start`
        for (int i = start; i < (int)nums.size(); ++i) {
            swap(nums[start], nums[i]);      // choose
            backtrack(nums, start + 1, result);
            swap(nums[start], nums[i]);      // undo
        }
    }

public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> result;
        backtrack(nums, 0, result);
        return result;
    }
};
Time O(n * n!) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    void dfs(vector<vector<int>>& res, vector<int>& cur, int n, int idx) {
        if(idx==n-1) {
            res.push_back(cur);
            return;
        }

        for(int i=idx; i<n; ++i) {
            swap(cur[idx], cur[i]);
            dfs(res, cur, n, idx+1);
            swap(cur[idx], cur[i]);
        }
    }

    vector<vector<int>> permute(vector<int>& nums) {
        int n=nums.size();
        vector<vector<int>> res;
        dfs(res, nums, n, 0);
        return res;
    }
};

// Time Complexity: O(N!)
// Space Complexity: O(N)
Time O(N!) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern