Skip to content

Commit

Permalink
geeksforgeeks: add lexicographically next string
Browse files Browse the repository at this point in the history
  • Loading branch information
minizilla committed Dec 13, 2023
1 parent ef73a72 commit dbd72eb
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
15 changes: 15 additions & 0 deletions geeksforgeeks/lexicographically-next-string/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Lexicographically next string

Given a string, find lexicographically next string.
If string is empty, we return ‘a’.
If string contains all characters as ‘z’, we append ‘a’ at the end.
Otherwise we find first character from end which is not z and increment it.

## Copyright Notice

This problem is based on [content](https://www.geeksforgeeks.org/lexicographically-next-string/)
from [GeeksforGeeks](https://www.geeksforgeeks.org)
written by GeeksforGeeks
and subject to [GeeksforGeeks copyright](https://www.geeksforgeeks.org/legal/copyright-information/).
The original content from GeeksforGeeks and any modifications made here are attributed to GeeksforGeeks contributors,
and this work is shared under [CC BY-SA 4.0](../LICENSE).
23 changes: 23 additions & 0 deletions geeksforgeeks/lexicographically-next-string/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package lexicographically_next_string

import "strings"

func Solution(s string) string {
i := len(s) - 1
for i >= 0 && s[i] == 'z' {
i--
}

if i == -1 {
return s + "a"
}

j := 0
return strings.Map(func(r rune) rune {
if j == i {
r += 1
}
j++
return r
}, s)
}
29 changes: 29 additions & 0 deletions geeksforgeeks/lexicographically-next-string/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package lexicographically_next_string_test

import (
"testing"

sut "github.com/minizilla/minmax/geeksforgeeks/lexicographically-next-string"
"github.com/minizilla/testr"
)

func TestLexicographicallyNextString(t *testing.T) {
tests := map[string]struct {
in, out string
}{
"empty": {"", "a"},
"a": {"a", "b"},
"z": {"z", "za"},
"ab": {"ab", "ac"},
"az": {"az", "bz"},
"zz": {"zz", "zza"},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
assert := testr.New(t)
out := sut.Solution(tc.in)
assert.Equal(out, tc.out)
})
}
}

0 comments on commit dbd72eb

Please sign in to comment.