File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22import epi .test_framework .EpiTest ;
33import epi .test_framework .GenericTest ;
44
5+ import java .util .ArrayList ;
6+ import java .util .Collections ;
57import java .util .List ;
8+
69public 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 ) {
Original file line number Diff line number Diff 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" : {
You can’t perform that action at this time.
0 commit comments