Reverse a string

Programming

In this programming tutorial we are going to find the reverse of a string.

Problem statement

We are given a string say "Hello World" and we have to print the reverse of it.

Solution

So, first we save the string in a 1D array which will look something like the following.

Hello World

+------------+---+---+---+---+---+---+---+---+---+---+---+
| index      | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10|
+------------+---+---+---+---+---+---+---+---+---+---+---+
| characters | H | e | l | l | o |   | W | o | r | l | d |
+------------+---+---+---+---+---+---+---+---+---+---+---+

Now, to reverse the string we can set two markers, one at the start (0th index) and the other at the end (10th index).

Next, we compute the middle index.

middle = (start + end) / 2

Note! The value of middle is a floor value. So, if we get 2.5 then we take 2.

We will move the start from left to right towards the middle - 1 index. And we will move the end index from right to left towards the middle index. And we will keep swapping the characters at index start with index end.

Code

Python

s = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

print('before', s)

start = 0
end = len(s) - 1
while start < end:
    s[start], s[end] = s[end], s[start]
    start += 1
    end -= 1

print('after', s)

Output

before ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
after ['d', 'l', 'r', 'o', 'W', ' ', 'o', 'l', 'l', 'e', 'H']

Time complexity

This has time complexity of O(n).

Feel free to try this out in other programming languages. Have fun coding.