Tuesday, February 17, 2009

Reverse a string

This is one of my favourite and has several correct solutions.

2. Reverse a string.

The best way would be to loop through half of the sting and swap the characters at either end (without using an extra variable!)

2 comments:

Varunkumar Nagarajan said...

Hey Sunil,

This solution needs to know the length of the string before actually doing the swapping. Basically, we need to scan the string twice (One for length, one for swapping[half]). It will come to O(n+n/2).

Is there any way we can do it in a single scan??

rogue said...

I've not come across any way of doing it in O(n/2) or O(n) yet. Shall try to dig out something.