Skip to content

Commit 9dbbf68

Browse files
committed
034
1 parent c3886c7 commit 9dbbf68

File tree

4 files changed

+60
-0
lines changed

4 files changed

+60
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,5 @@ Number | Difficulty | Asked By
5050
[#31](problem031) | EASY | Google
5151
[#32](problem032) | HARD | Jane Street
5252
[#33](problem033) | EASY | Microsoft
53+
[#34](problem034) | MEDIUM | Quora
5354

problem034/README.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
## Daily Coding Problem: Problem #34 [MEDIUM]
2+
3+
Good morning! Here's your coding interview problem for today.
4+
5+
This problem was asked by Quora.
6+
7+
Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically).
8+
9+
For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically.
10+
11+
As another example, given the string "google", you should return "elgoogle".

problem034/problem034.go

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package problem034
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func minString(s1 string, s2 string) string {
8+
if s1 <= s2 {
9+
return s1
10+
}
11+
return s2
12+
}
13+
14+
func ClosestPalindrome(word string) string {
15+
if len(word) <= 1 {
16+
return word
17+
}
18+
19+
firstCharacter, lastCharacter := word[0], word[len(word)-1]
20+
if firstCharacter == lastCharacter {
21+
return fmt.Sprintf("%c%s%c", firstCharacter, ClosestPalindrome(word[1:len(word)-1]), lastCharacter)
22+
}
23+
24+
candidate1 := fmt.Sprintf("%c%s%c", firstCharacter, ClosestPalindrome(word[1:]), firstCharacter)
25+
candidate2 := fmt.Sprintf("%c%s%c", lastCharacter, ClosestPalindrome(word[:len(word)-1]), lastCharacter)
26+
if len(candidate1) < len(candidate2) {
27+
return candidate1
28+
} else if len(candidate1) == len(candidate2) {
29+
return minString(candidate1, candidate2)
30+
} else {
31+
return candidate2
32+
}
33+
}

problem034/problem034_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package problem034
2+
3+
import "testing"
4+
5+
func TestClosestPalindrome(t *testing.T) {
6+
result := ClosestPalindrome("race")
7+
if result != "ecarace" {
8+
t.Fail()
9+
}
10+
11+
result = ClosestPalindrome("google")
12+
if result != "elgoogle" {
13+
t.Fail()
14+
}
15+
}

0 commit comments

Comments
 (0)