Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Generate the 'look-and-say' sequence starting from '1'.
Problem: Generate the 'look-and-say' sequence starting from '1'.
def nxt(s):
out, i = [], 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]: j += 1
out.append(str(j - i) + s[i]); i = j
return "".join(out)
s = "1"
for _ in range(5): s = nxt(s)
print(s)What is printed?- A. 111221
- B. 13112221
- C. 312221
- D. 312211
Correct answer: D. 312211
Terms: 1 → 11 → 21 → 1211 → 111221 → 312211 (three 1s, two 2s, one 1). After 5 steps we are at the 6th term.
More Coding Interview Problems questions
- Problem: Print a matrix in spiral order. python def spiral(m): res = [] while m: res += m.pop(0) m = [list(r) for r in zip(m)][::-1]…
- Problem: Run Conway's Game of Life on an unbounded board (a live cell survives with 2 or 3 live neighbours; a dead cell becomes live with…
- In the Tower of Hanoi with 5 discs and 3 pegs A, B, C in a row, moves are allowed only between ADJACENT pegs (A↔B, B↔C, never A↔C…
- Problem: Count the integers in [1, 1000] that are coprime to 1000. python from math import gcd print(sum(1 for i in range(1, 1001) if…
- Reservoir sampling keeps k = 2 items from a stream of n = 10 items: the first 2 fill the reservoir, and item i (i > 2) is admitted with…
- Problem: An LFU cache (capacity 2) evicts the least frequently used key; ties are broken by least recently used. get returns −1 on a miss…