Go Program to Check Palindrome String
for i := 0; i < len(s)/2; i++ { if s[i] != s[len(s)-1-i] { return false } }.Examples
How to Think About It
Algorithm
Code
package main import ( "fmt" ) func isPalindrome(s string) bool { for i := 0; i < len(s)/2; i++ { if s[i] != s[len(s)-1-i] { return false } } return true } func main() { input := "madam" if isPalindrome(input) { fmt.Println(input, "is a palindrome") } else { fmt.Println(input, "is not a palindrome") } }
Dry Run
Let's trace the string "madam" through the palindrome check.
Start loop
i = 0, compare s[0] = 'm' with s[4] = 'm' - they match
Next iteration
i = 1, compare s[1] = 'a' with s[3] = 'a' - they match
Loop ends
Reached middle of string, all pairs matched, return true
| i | s[i] | s[len(s)-1-i] | Match? |
|---|---|---|---|
| 0 | m | m | Yes |
| 1 | a | a | Yes |
Why This Works
Step 1: Compare characters from ends
The code compares characters starting from the first and last positions moving inward using s[i] and s[len(s)-1-i].
Step 2: Stop early if mismatch
If any pair of characters does not match, the function immediately returns false, saving time.
Step 3: Return true if all match
If the loop finishes without mismatches, the string is a palindrome, so the function returns true.
Alternative Approaches
package main import ( "fmt" ) func isPalindrome(s string) bool { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return s == string(runes) } func main() { input := "madam" if isPalindrome(input) { fmt.Println(input, "is a palindrome") } else { fmt.Println(input, "is not a palindrome") } }
package main import ( "fmt" ) func isPalindromeRecursive(s string, start, end int) bool { if start >= end { return true } if s[start] != s[end] { return false } return isPalindromeRecursive(s, start+1, end-1) } func main() { input := "madam" if isPalindromeRecursive(input, 0, len(input)-1) { fmt.Println(input, "is a palindrome") } else { fmt.Println(input, "is not a palindrome") } }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs up to half the string length, so time is proportional to the string size, O(n).
Space Complexity
The check uses no extra space besides variables, so space is O(1).
Which Approach is Fastest?
The direct character comparison loop is fastest and uses least memory compared to reversing or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct loop comparison | O(n) | O(1) | Fastest and memory efficient |
| Reverse and compare | O(n) | O(n) | Simple but uses extra memory |
| Recursive check | O(n) | O(n) | Elegant but uses call stack |