Maximum consecutive integers present in an array
October 14, 2018
Reverse only the alphabets in a string
March 13, 2019

Reverse a string

Write a simple code to reverse a string.

INPUT: "HELLO WORLD"
OUTPUT: "DLROW OLLEH"

The logic to reverse a string is simple, swap the first character with last character, the second character with the second-last character and so on…

Take two variables low and high to hold the indices of first and last element, increment low and decrement high as long as low<high.

CODE:

void reverse(char* str, int n) 
{
if(str == NULL || n <= 1)
return;
int low = 0;
int high = n-1;

while(low < high)
{
char temp = str[low];
str[low] = str[high];
str[high] = temp;
low++;
high--;
}
}

The code traverse the string only once and takes O(n) time.

Leave a Reply

Your email address will not be published. Required fields are marked *