Skip to content

Commit 8794ccc

Browse files
committed
5.11 Next Perm - Add initial attempt (swap & sort)
1 parent 347d807 commit 8794ccc

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

epi_judge_java/epi/NextPermutation.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,29 @@
22
import epi.test_framework.EpiTest;
33
import epi.test_framework.GenericTest;
44

5+
import java.util.ArrayList;
6+
import java.util.Collections;
57
import java.util.List;
8+
69
public class NextPermutation {
710
@EpiTest(testDataFile = "next_permutation.tsv")
811
public static List<Integer> nextPermutation(List<Integer> perm) {
9-
// TODO - you fill in here.
10-
return null;
12+
// Initial Attempt - Swapping & sorting to get next perm
13+
// Time: O(nlogn), Space: O(1)
14+
for (int i = perm.size() - 1; i > 0; i--) {
15+
if (perm.get(i-1) < perm.get(i)) {
16+
int di = i - 1; // Index of 1st non-conforming (decreasing) digit from the right
17+
int dk = i; // Index of smallest element bigger & to the right of perm[di]
18+
for (int j = i; j < perm.size(); j++) {
19+
if (perm.get(j) > perm.get(di) && perm.get(j) < perm.get(dk))
20+
dk = j;
21+
}
22+
Collections.swap(perm, di, dk);
23+
Collections.sort(perm.subList(di + 1, perm.size())); // Sort all elements after perm[di]
24+
return perm;
25+
}
26+
}
27+
return new ArrayList<>();
1128
}
1229

1330
public static void main(String[] args) {

problem_mapping.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ problem_mapping = {
330330
"total": 2001
331331
},
332332
"Java: NextPermutation.java": {
333-
"passed": 0,
333+
"passed": 2001,
334334
"total": 2001
335335
},
336336
"Python: next_permutation.py": {

0 commit comments

Comments
 (0)