Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Next Permutation of Array
Optimal Algorithm



Problem Statement

Given an array of integers, your task is to rearrange the elements to form the next lexicographical permutation of the array.

This must be done in-place, meaning you cannot use extra memory for another array.

Examples

Input ArrayNext PermutationDescription
[1, 2, 3][1, 3, 2]Normal case: 1-2-3 → 1-3-2 is the next permutation
[3, 2, 1][1, 2, 3]Already the largest permutation, so return smallest (reverse sort)
[1, 1, 5][1, 5, 1]Duplicates are handled: swap to get next valid permutation
[1][1]Single element, no next permutation possible
[][]Empty array, return as-is
[1, 3, 2][2, 1, 3]Mid permutation: find pivot and rearrange
[2, 3, 1][3, 1, 2]Pivot is at index 0, swap with just larger and reverse rest

Solution

The goal of this problem is to find the next permutation in dictionary (lexicographical) order. Think of all permutations of the array elements being sorted — your task is to move to the very next one in that sorted list.

Let’s discuss how this works and what outcomes we may expect, depending on the input.

🧩 Case 1: Normal Next Permutation Exists

Suppose the array is not in the highest possible order. We can still find a next greater permutation. To do that:

  • We look from right to left and find the first element that is smaller than its right neighbor. This element is our pivot.
  • Then we look again from the right and find the smallest element that is larger than the pivot — and we swap them.
  • Finally, we reverse the subarray after the pivot to get the smallest possible arrangement following the pivot.

This gives us the next greater permutation.

Case 2: Already the Last Permutation

If the array is in descending order (like [3, 2, 1]), it is already the last permutation. There's no greater permutation possible. In this case, the next permutation is just the smallest one — so we sort the array in ascending order.

🔄 Case 3: Duplicates Present

Even if the array has repeated numbers, the same logic applies. For example, in [1, 1, 5], the pivot is the first 1, and the next greater element is 5. We swap them and reverse the rest to get [1, 5, 1].

Case 4: Single Element or Empty Array

  • For a single element array, there is no rearrangement possible. So the array remains the same.
  • For an empty array, we return it as-is. There’s no permutation to perform.

Summary

This optimal solution works in linear time and does not use extra space. It’s based on the observation that the next permutation is formed by modifying the suffix of the array in a smart way. By finding a pivot, swapping, and reversing a part of the array, we efficiently jump to the next valid permutation.

Visualization

Algorithm Steps

  1. Given an array arr of integers.
  2. Start from the end and find the first index i where arr[i] < arr[i+1]. This identifies the pivot.
  3. If no such index exists, reverse the entire array to get the lowest permutation.
  4. Otherwise, find the next larger element than arr[i] from the end of the array, say index j, and swap arr[i] and arr[j].
  5. Finally, reverse the subarray from i+1 to the end to get the next permutation.

Code

Python
JavaScript
Java
C++
C
def next_permutation(arr):
    n = len(arr)
    i = n - 2
    while i >= 0 and arr[i] >= arr[i + 1]:
        i -= 1
    if i >= 0:
        j = n - 1
        while arr[j] <= arr[i]:
            j -= 1
        arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1:] = reversed(arr[i + 1:])
    return arr

# Sample Input
arr = [1, 2, 3]
print("Next Permutation:", next_permutation(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)In the best case, we still need to scan from the end to find the pivot, and possibly reverse a subarray — all in linear time.
Average CaseO(n)On average, the algorithm scans the array from the end to find the pivot and the next greater element, followed by a reversal — all linear operations.
Average CaseO(n)In the worst case, such as when the array is in descending order, we have to reverse the entire array — still a linear time operation.

Space Complexity

O(1)

Explanation: The algorithm modifies the array in-place without using any extra space except a few variables for indices and swapping.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M