arcbjorn

thoughtbook

Monday, December 19, 2022

Reverse string

Leetcode 344 problem.

A function that reverses a string. The input string is given as an array of characters (bytes) s.

Go

  • Time complexity: O(n)O(n) - n is a length of a string
  • Auxiliary space: O(1)O(1) - constant amount of space
func reverseString(s []byte) string {
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }
    return string(s)
}
Creative Commons Licence