Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Write a string in a zigzag over r rows (down, then diagonally up) and read it row by row.

Problem: Write a string in a zigzag over r rows (down, then diagonally up) and read it row by row.
def zigzag(s, rows):
    if rows == 1: return s
    r = [""] * rows; i, step = 0, 1
    for c in s:
        r[i] += c
        if i == 0: step = 1
        elif i == rows - 1: step = -1
        i += step
    return "".join(r)
print(zigzag("PROGRAMMING", 3), zigzag("ABCDEFG", 4))
What is printed?
  1. A. PRIRGAMNOMG ADGBECF
  2. B. PRIRGAMNOGM AGBFCED
  3. C. POMRGAMNRIG AGBFCED
  4. D. PRIRGAMNOMG AGBFCED

Correct answer: D. PRIRGAMNOMG AGBFCED

Row indices cycle 0, 1, 2, 1, 0, 1, 2, … For "PROGRAMMING": row 0 = P, R, I; row 1 = R, G, A, M, N; row 2 = O, M, G. With 4 rows the pattern 0, 1, 2, 3, 2, 1, 0 gives AG | BF | CE | D. The rows == 1 guard prevents step from oscillating out of range. O(n).

More Coding Interview Problems questions

Exams that ask this topic