Skip to content
Programs · Program 8-3

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.

Uttarakhand UbseTextbookSubjective· 3mImportance★★★★★est
31% · 4/13 Questions
🔒 Locked · start free trial →

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 O(1)O(1) extra space (a constant amount of memory, like a few variables), and modifying the original string directly.

The algorithm works like this:

  1. Let the string have length nn.
  2. Place one pointer at index 00 (left) and another at index n−1n-1 (right).
  3. 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 nn, the number of swaps is ⌊n/2⌋\lfloor n/2 \rfloor. If nn is odd, the middle character stays where it is — no swap needed.

Important

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.