Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Restore all valid IPv4 addresses from a digit string (four parts, each 0–255, no leading zeros except "0").
Problem: Restore all valid IPv4 addresses from a digit string (four parts, each 0–255, no leading zeros except "0").
def restore(s):
res = []
def bt(i, parts):
if len(parts) == 4:
if i == len(s): res.append(".".join(parts))
return
for L in (1, 2, 3):
seg = s[i:i + L]
if len(seg) < L: break
if (seg[0] == "0" and L > 1) or int(seg) > 255: continue
bt(i + L, parts + [seg])
bt(0, [])
return res
print(len(restore("192168011")), restore("10023"))What is printed?- A. 3 ['1.0.0.23', '1.0.02.3', '10.0.2.3']
- B. 3 ['1.0.0.23', '10.0.2.3', '100.2.3']
- C. 4 ['1.0.0.23', '10.0.2.3']
- D. 3 ['1.0.0.23', '10.0.2.3']
Correct answer: D. 3 ['1.0.0.23', '10.0.2.3']
Each part takes 1–3 digits, so there are at most 3⁴ = 81 branches – effectively O(1). "10023": '1.0.02.3' and '1.00.2.3' are rejected for leading zeros, and '100.2.3' has only three parts; the valid ones are 1.0.0.23 and 10.0.2.3. "192168011" yields 3 addresses; one is 192.168.0.11, while 192.168.01.1 is rejected.
More Coding Interview Problems questions
- Problem: Return every value an arithmetic expression can take under all possible full parenthesisations (divide and conquer on each…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a…
- Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the…
- Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a…
- Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on…
- Problem: Print the top view of a tree (the first node seen in each vertical column, left to right; root column 0, left child −1, right…