githubEdit

26. Generate Permutations of an Array

βœ… GFG solution to the Generate Permutations problem: find all possible permutations of array elements using backtracking and STL algorithms. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given an array arr[] of unique elements. Your task is to generate all possible permutations of the elements in the array.

A permutation is an arrangement of all elements where order matters. For an array of n elements, there are n! (n factorial) possible permutations.

πŸ“˜ Examples

Example 1

Input: arr[] = [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Explanation: There are 6 possible permutations (3! = 6) of the array.

Example 2

Input: arr[] = [1, 3]
Output: [[1, 3], [3, 1]]
Explanation: There are 2 possible permutations (2! = 2) of the array.

πŸ”’ Constraints

  • $1 \le \text{arr.size()} \le 9$

βœ… My Approach

The optimal approach uses STL's next_permutation function which generates permutations in lexicographic order:

STL next_permutation Approach

  1. Sort the Array:

    • First sort the array to get the lexicographically smallest permutation.

    • This ensures we start from the beginning and generate all permutations systematically.

  2. Generate Permutations:

    • Use next_permutation() which rearranges elements to the next lexicographically greater permutation.

    • Store each permutation in the result vector.

  3. Continue Until All Generated:

    • The next_permutation() function returns false when no more permutations exist (when array is in descending order).

    • This automatically handles generation of all n! permutations.

  4. Return Result:

    • Return the collected permutations.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n! Γ— n), as we generate n! permutations and each permutation requires O(n) time to copy into the result. The next_permutation() function itself operates in O(n) time per call.

  • Expected Auxiliary Space Complexity: O(1), as we only use constant extra space for the algorithm (excluding the output storage). The sorting and permutation generation happen in-place.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Backtracking with Swap Approach

πŸ’‘ Algorithm Steps:

  1. Use recursion with index-based swapping to generate permutations.

  2. At each recursion level, swap current element with all elements from current index to end.

  3. Recursively generate permutations for remaining elements.

  4. Backtrack by swapping elements back to restore original state.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n! Γ— n) - Generating all permutations and copying each

  • Auxiliary Space: πŸ’Ύ O(n) - Recursion stack depth

βœ… Why This Approach?

  • Classic backtracking pattern for permutations

  • In-place swapping reduces space overhead

  • Easy to understand recursion flow

πŸ“Š 3️⃣ Iterative Heap's Algorithm

πŸ’‘ Algorithm Steps:

  1. Use Heap's algorithm to generate permutations iteratively without recursion.

  2. Maintain a counter array to track swap positions at each level.

  3. Generate permutations by systematic swapping based on counter values.

  4. Continue until all permutations are generated.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n! Γ— n) - All permutations with copying

  • Auxiliary Space: πŸ’Ύ O(n) - Counter array only

βœ… Why This Approach?

  • No recursion overhead, purely iterative

  • Efficient systematic generation pattern

  • Optimal for memory-constrained environments

πŸ“Š 4️⃣ Manual next_permutation Implementation

πŸ’‘ Algorithm Steps:

  1. Sort array to start from lexicographically smallest permutation.

  2. Find rightmost ascending pair from end of array.

  3. Swap pivot with smallest element greater than it from right.

  4. Reverse suffix after pivot position to get next permutation.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n! Γ— n) - Each permutation generation is O(n)

  • Auxiliary Space: πŸ’Ύ O(1) - In-place modifications

βœ… Why This Approach?

  • Generates permutations in lexicographic order

  • Educational value in understanding algorithm internals

  • No recursion stack overhead

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ STL next_permutation

🟒 O(n! Γ— n)

🟒 O(1)

πŸš€ Clean and concise

πŸ”§ Requires sorting first

πŸ” Backtracking Swap

🟒 O(n! Γ— n)

🟑 O(n)

πŸ“– Intuitive recursion

πŸ’Ύ Recursion stack space

πŸ“Š Heap's Algorithm

🟒 O(n! Γ— n)

🟒 O(n)

🎯 No recursion overhead

🐌 Complex iteration logic

πŸ”„ Manual next_permutation

🟒 O(n! Γ— n)

🟒 O(1)

⭐ Lexicographic order

πŸ”§ Longer implementation

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Production code simplicity

πŸ₯‡ STL next_permutation

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning/Interview context

πŸ₯ˆ Backtracking Swap

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Avoiding recursion

πŸ₯‰ Heap's Algorithm

β˜…β˜…β˜…β˜…β˜†

🎯 Lexicographic order required

πŸ… Manual next_permutation

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated