⬅ Previous Topic
Rearrange Array Alternating Positive and Negative ElementsNext Topic ⮕
Leaders in an Array⬅ Previous Topic
Rearrange Array Alternating Positive and Negative ElementsNext Topic ⮕
Leaders in an ArrayTopic Contents
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.
arr
of integers.i
where arr[i] < arr[i+1]
. This identifies the pivot.arr[i]
from the end of the array, say index j
, and swap arr[i]
and arr[j]
.i+1
to the end to get the next permutation.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))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(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 Case | O(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 Case | O(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. |
O(1)
Explanation: The algorithm modifies the array in-place without using any extra space except a few variables for indices and swapping.
⬅ Previous Topic
Rearrange Array Alternating Positive and Negative ElementsNext Topic ⮕
Leaders in an ArrayYou 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.