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?
  1. A. True False True
  2. B. True False False
  3. C. False False True
  4. 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

Exams that ask this topic