Reversing a string in place — Pseudocode Aptitude Question
Reversing a string in place: Characters are numbered from 1 and / is integer division. What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 150 seconds
Question
Characters are numbered from 1 and / is integer division. What is printed?
String s
Integer i, n, t
Set s = "ALGORITHM"
Set n = length(s)
For i = 1 to n / 2
Set t = s[i]
Set s[i] = s[n - i + 1]
Set s[n - i + 1] = t
End For
Print sOptions
- ALGORITHM
- HTIROGLAM
- MHTIROGLA
- AMHTIROGL
Show the answer and the worked solution
Correct answer: C. MHTIROGLA
Worked solution
- n = 9, so the loop runs for i = 1 to 4 and position 5 is left alone.
- The pairs exchanged are (1, 9), (2, 8), (3, 7) and (4, 6).
- Starting from A L G O R I T H M those swaps produce M H T I R O G L A.
- The printed string is MHTIROGLA.
Answer: MHTIROGLA.
The idea
In-place reversal swaps position i with n − i + 1 under 1-based numbering, and only half the string needs visiting. Using n − i instead is the classic off-by-one and yields HTIROGLAM, which is offered as a distractor.
Shortcut. The first letter must end up last and the last first, so the answer starts with M and ends with A, and only MHTIROGLA does.
Common trap. "ALGORITHM" assumes every pair is swapped twice and so restored, which would happen only if the loop ran to n; stopping at n / 2 swaps each pair once.