AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardstringsswapping

~150s

Reversing a string in place

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 s
Show the answer and the worked solution

Correct answer: C.

MHTIROGLA

Worked solution

  1. n = 9, so the loop runs for i = 1 to 4 and position 5 is left alone.
  2. The pairs exchanged are (1, 9), (2, 8), (3, 7) and (4, 6).
  3. Starting from A L G O R I T H M those swaps produce M H T I R O G L A.
  4. 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.

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.

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 s

Options

  1. ALGORITHM
  2. HTIROGLAM
  3. MHTIROGLA
  4. AMHTIROGL
Show the answer and the worked solution

Correct answer: C. MHTIROGLA

Worked solution

  1. n = 9, so the loop runs for i = 1 to 4 and position 5 is left alone.
  2. The pairs exchanged are (1, 9), (2, 8), (3, 7) and (4, 6).
  3. Starting from A L G O R I T H M those swaps produce M H T I R O G L A.
  4. 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.

All Pseudocode questions · placement mock tests