Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …).
Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …).
def say(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 = say(s)
print(s, say("3322251"))What is printed?- A. 312211 2332251
- B. 312211 23321511
- C. 111221 23321511
- D. 13112221 23321511
Correct answer: B. 312211 23321511
Terms: 1 → 11 → 21 → 1211 → 111221 → 312211 (five steps). "3322251" = two 3s, three 2s, one 5, one 1 → "23" "32" "15" "11". Each step is linear in the term length; terms grow by about 30% per step.
More Coding Interview Problems questions
- Problem: Write a string in a zigzag over r rows (down, then diagonally up) and read it row by row. python def zigzag(s, rows): if rows ==…
- 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…