File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
main/kotlin/common/twopointers/nextlexicographicalsequence
test/kotlin/common/twopointers/nextlexicographicalsequence Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ package common.twopointers.nextlexicographicalsequence
2
+
3
+ class NextLexicographicalSequence {
4
+
5
+ fun solution (s : String ): String {
6
+ val letters = s.toCharArray()
7
+
8
+ // Locate the pivot, which is the first character from the right that breaks
9
+ // non-increasing order. Start searching from the second-to-last position,
10
+ // since the last character is neither increasing nor decreasing.
11
+ var pivot = letters.size - 2
12
+ while (pivot >= 0 && letters[pivot] >= letters[pivot + 1 ]) {
13
+ pivot--
14
+ }
15
+
16
+ // If pivot is not found, the string is already in its largest permutation. In
17
+ // this case, reverse the string to obtain the smallest permutation.
18
+ if (pivot == - 1 ) {
19
+ letters.reverse()
20
+ return letters.joinToString(" " )
21
+ }
22
+
23
+ // Find the rightmost successor to the pivot.
24
+ var rightmostSuccessor = letters.size - 1
25
+ while (letters[rightmostSuccessor] <= letters[pivot]) {
26
+ rightmostSuccessor--
27
+ }
28
+
29
+ // Swap the rightmost successor with the pivot to increase the lexicographical
30
+ // order of the suffix.
31
+ letters[pivot] = letters[rightmostSuccessor].also { letters[rightmostSuccessor] = letters[pivot] }
32
+
33
+ // Reverse the suffix after the pivot to minimize its permutation.
34
+ val suffix = letters.sliceArray(pivot + 1 until letters.size)
35
+ suffix.reverse()
36
+
37
+ return (letters.sliceArray(0 .. pivot) + suffix).joinToString(" " )
38
+ }
39
+ }
Original file line number Diff line number Diff line change
1
+ package common.twopointers.nextlexicographicalsequence
2
+
3
+ import org.junit.jupiter.api.Test
4
+ import kotlin.test.assertEquals
5
+
6
+ class NextLexicographicalSequenceTest {
7
+
8
+ private val question = NextLexicographicalSequence ()
9
+
10
+ @Test
11
+ fun `Verify solution` () {
12
+ assertEquals(" a" , question.solution(" a" ))
13
+ assertEquals(" aaaa" , question.solution(" aaaa" ))
14
+ assertEquals(" ynsdeit" , question.solution(" ynitsed" ))
15
+ assertEquals(" nuash" , question.solution(" nuahs" ))
16
+ assertEquals(" abdc" , question.solution(" abcd" ))
17
+ assertEquals(" abcd" , question.solution(" dcba" ))
18
+ }
19
+ }
You can’t perform that action at this time.
0 commit comments