ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (+ joins strings)

What will be the output of the following pseudocode? (+ joins strings)
String s = "PAYPALISHIRING"
Integer rows = 3, r = 0, step = 1
String line[3] = {"", "", ""}
for (each ch in s)
    line[r] = line[r] + ch
    if (r == 0) step = 1
    if (r == rows - 1) step = -1
    r = r + step
end for
Print line[0] + line[1] + line[2]
  1. A. PAHNAPLSIIGYIR
  2. B. PAYPALISHIRING
  3. C. PYAIHRNAPLSIIG
  4. D. PAHNPLSIIGAYIR

Correct answer: A. PAHNAPLSIIGYIR

Characters go down rows 0, 1, 2 and back up 1, 0, … in a zigzag. Row 0: P A H N; row 1: A P L S I I G; row 2: Y I R. Joined: PAHNAPLSIIGYIR.

More Pseudocode and Code Tracing questions

Exams that ask this topic