1. Generate All Permutations in Lexicographical Order
Intuition
Generate all N! permutations recursively, sort them lexicographically, and find the successor.
Algorithm
- 1. Use backtracking/recursion to generate all N! permutations.
- 2. Sort the generated permutations in lexicographical order.
- 3. Search for current configuration and pick the next index (modulo total count).
- 4. Total runtime is O(N! * N) and space is O(N!).
Brute Force All Permutations Generation Trace
2 of 2 questions left todayGenerate Permutations: Recursively build lexicographical list starting from [1, 2, 3, 4, 5]
Generate Permutations: Recursively build lexicographical list starting from [1, 2, 3, 4, 5].
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: void nextPermutation(vector<int>& nums) { std::next_permutation(nums.begin(), nums.end()); }}; int main() { Solution sol; vector<int> nums = {1, 2, 3}; sol.nextPermutation(nums); cout << "Next Permutation: "; for (int x : nums) cout << x << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N! * N)— Generating and sorting N! permutations of length N requires factorial time and space. - Space complexity:
O(N! * N)— Requires auxiliary space to store all N! permutation arrays.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.