Skip to content

Commit e2fd54e

Browse files
authored
Merge pull request #683 from shankr4444/shankr4444-patch-2
Added Solution for LeetCode Problem No. 31
2 parents 4b35bf6 + f5e976d commit e2fd54e

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// https://leetcode.com/problems/next-permutation/
2+
3+
class Solution {
4+
public void nextPermutation(int[] nums) {
5+
/*
6+
Approach:
7+
1. We loop from the end to the point where the value of the element is just smaller than the previous digit.
8+
2. Then We loop from the end to that point and find the element which is just greater than the element.
9+
3. We swap the two elements.
10+
4. Finally we reverse the sequence from end to the index of the point + 1;
11+
*/
12+
13+
int lastIndex = nums.length - 2; // For Comparing The Element With the Next Element
14+
int swapIndex = nums.length - 1; // For Swapping Value With The Element Just Greater.
15+
16+
// Finding The Index Of The First Smaller Element Than Previous
17+
while(lastIndex >= 0 && nums[lastIndex] >= nums[lastIndex + 1]){
18+
lastIndex--;
19+
}
20+
21+
// Swapping The Number With The Previous Just Greater Value
22+
if(lastIndex >= 0){
23+
24+
while(nums[swapIndex] <= nums[lastIndex]){
25+
swapIndex--;
26+
}
27+
28+
swap(nums, lastIndex, swapIndex);
29+
30+
}
31+
32+
// Reversing All Elements Behind The Number
33+
// In The Edge Case Of The Number Being In Descending Order, The Whole Number Will Be Reversed
34+
reverse(nums, lastIndex+1);
35+
36+
}
37+
38+
//Swap Function
39+
public void swap(int[] nums, int i, int j){
40+
41+
int temp = nums[i];
42+
nums[i] = nums[j];
43+
nums[j] = temp;
44+
45+
}
46+
47+
// Reverse Function
48+
public void reverse(int[] nums, int i){
49+
50+
int j = nums.length - 1;
51+
52+
while(i<j){
53+
swap(nums, i, j);
54+
i++;
55+
j--;
56+
}
57+
58+
}
59+
60+
}

0 commit comments

Comments
 (0)