Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions challenge-2/submissions/Johrespi/solution-template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
// Read input from standard input
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
input := scanner.Text()

// Call the ReverseString function
output := ReverseString(input)

// Print the result
fmt.Println(output)
}
}

// ReverseString returns the reversed string of s.
func ReverseString(s string) string {
// TODO: Implement the function
var output string
for c := len(s) - 1; c >= 0; c-- {
output += string(s[c])
}
return output
}
Comment on lines +24 to +31
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fix critical Unicode bug: byte indexing breaks multi-byte UTF-8 characters.

The current implementation treats the string as a byte array by indexing with s[c]. This corrupts multi-byte UTF-8 characters like emojis, accented letters, or non-ASCII text. For example, reversing "café" or "Hello 👋" will produce garbled output.

Additionally, string concatenation in a loop has O(n²) time complexity because strings are immutable in Go.

Apply this diff to fix both issues:

-// ReverseString returns the reversed string of s.
 func ReverseString(s string) string {
-	// TODO: Implement the function
-	var output string
-	for c := len(s) - 1; c >= 0; c-- {
-	    output += string(s[c])
-	}
-	return output
+	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 string(runes)
 }

This solution:

  • Converts the string to a rune slice to properly handle Unicode characters
  • Uses in-place swapping for O(n) time complexity
  • Removes the obsolete TODO comment

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In challenge-2/submissions/Johrespi/solution-template.go around lines 24 to 31,
the current implementation indexes the string by bytes and concatenates in a
loop, which corrupts multi-byte UTF-8 characters and is O(n²); fix by converting
the input string to a rune slice, perform in-place swapping of runes
(two-pointer swap from ends toward center) to reverse in O(n) time, then return
a new string created from the rune slice, and remove the obsolete TODO comment.

Loading