Problem Statement:
Given an array of integers nums, find the next permutation of nums.
The replacement must be in place and use only constant extra memory.
My Approach:
1.By noticing a pattern that to get the next permutation that help me to solve the problem in easier way that I need to make the number slightly bigger than the current one.
2.Then I start from the end and find the first number smaller than the one after it that is the pivot where the change should happen.
3.Then I look from the end again to find the first number bigger than the pivot and I swap them that this follows the pattern to make the next number slightly larger.
4.Then I reverse the part of the array after the pivot to make it ascending which completes the pattern for the next smallest permutation.
If the array is completely in descending order, I reverse the whole array to follow the pattern and get the smallest permutation.

Top comments (0)