Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Can all matchsticks form a square (every stick used exactly once)? Backtrack placing sticks (longest first) into 4 sides, skipping sides with equal current length.
Problem: Can all matchsticks form a square (every stick used exactly once)? Backtrack placing sticks (longest first) into 4 sides, skipping sides with equal current length.
def square(sticks):
total = sum(sticks)
if total % 4: return False
side = total // 4; sticks = sorted(sticks, reverse=True)
if sticks[0] > side: return False
sides = [0] * 4
def bt(i):
if i == len(sticks): return True
seen = set()
for k in range(4):
if sides[k] + sticks[i] <= side and sides[k] not in seen:
seen.add(sides[k]); sides[k] += sticks[i]
if bt(i + 1): return True
sides[k] -= sticks[i]
return False
return bt(0)
print(square([3, 3, 2, 2, 2, 1, 1, 2]), square([3, 3, 3, 3, 4]), square([5, 5, 5, 3, 2]))What is printed?- A. True False True
- B. True False False
- C. False False True
- D. True True True
Correct answer: A. True False True
Side = total / 4. [3, 3, 2, 2, 2, 1, 1, 2] (side 4): 3+1, 3+1, 2+2, 2+2. [3, 3, 3, 3, 4] has total 16 and every stick ≤ 4, but a side of 4 can only be the 4 alone; the 3s cannot pair up to 4 → False (passing the sum/max checks is not enough). [5, 5, 5, 3, 2]: 5, 5, 5, 3+2. Sorting descending and the 'seen' set prune symmetric branches; worst case O(4ⁿ).
More Coding Interview Problems questions
- Problem: Insert '+', '−' or '' between the digits (or leave digits joined) so the expression equals the target. Operands may not have…
- Problem: A thief robs houses arranged as a binary tree; robbing two directly linked houses triggers an alarm. Each node returns (best if…
- Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its…
- Problem: A tree of n nodes holds n coins in total, unevenly. A move transfers one coin between adjacent nodes. Minimum moves so every node…
- Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent…
- Problem: Rocks are smashed repeatedly: take the two heaviest; if equal both vanish, otherwise the difference remains. Report the last…