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?- A. PRIRGAMNOMG ADGBECF
- B. PRIRGAMNOGM AGBFCED
- C. POMRGAMNRIG AGBFCED
- 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
- Problem: Compare dotted version strings numerically part by part (missing parts count as 0); return 1, 0 or −1. python def cmpver(a, b): x…
- Problem: Multiply two non-negative integers given as decimal strings without converting them to int; digit i·j lands in position i + j + 1…
- Problem: Reverse the bit order of an 8-bit value (bit 0 ↔ bit 7, …). python def rev8(x): r = 0 for in range(8): r = (r << 1) | (x & 1); x…
- Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows. java int a…
- Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:]) in O(n), then use it on pattern + '' + text to…
- Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together…