Q.Program 8-3: Write a program to input a string from the user and print it in the reverse order without creating a new string.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Concept understanding — String Reversal In Place
String Reversal In Place
The Intuition
Imagine you have a word written on a whiteboard: C A T. Now you want to reverse it so it reads T A C. The most natural way is to swap the first and last letters, then move inward.
Swap C and T: T A C — done. That took one swap for a 3-letter word.
Now try B E A R. Swap B and R: R E A B. Swap E and A: R A E B. Two swaps for a 4-letter word.
Notice the pattern: you never need extra space. You're just swapping pairs of characters on the same board. That's the core idea of in-place reversal — you transform the string using only the memory it already occupies, without copying it to a new location.
The Precise Statement
String reversal in place means reversing the order of characters in a string using only extra space (a constant amount of memory, like a few variables), and modifying the original string directly.
The algorithm works like this:
- Let the string have length .
- Place one pointer at index (left) and another at index (right).
- While left < right:
- Swap the characters at left and right.
- Move left one step right, right one step left.
That's it. After the loop, the string is reversed.
Why It Works
Each swap puts a character from the left half into its mirror position on the right half, and vice versa. The pointers meet in the middle, and by then every pair has been swapped exactly once.
For a string of length , the number of swaps is . If is odd, the middle character stays where it is — no swap needed.
In languages like C or C++, strings are mutable (you can change individual characters). In Python or Java, strings are immutable — you cannot change them in place. For those languages, "in-place reversal" is done by converting the string to a list of characters first, reversing the list, then joining back. The list itself is modified in place.
A Concrete Example
Reverse "hello":
Initial: h e l l o
L R
Swap L and R: o e l l h …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.