Reverse a String
Easy · rating 950 · strings, implementation
Read a single line and print it reversed.
For input hello, print olleh.
Editorial
Approach
Swap characters from the two ends toward the middle with two pointers, or use your language's built-in reverse. The two-pointer version reverses in place with no extra allocation.
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1Complexity
Time: O(n). Space: O(1) in place.