coding
Airbnb
Amazon
Google

Airbnb Coding: Max Candies From Boxes (BFS/Greedy)

Topics:
Simulation
Greedy
BFS
Roles:
Software Engineer
Backend Engineer
SDE
Experience:
Entry Level
Mid Level
Senior

Question Description

You are given a set of numbered boxes, some unlocked and some locked, plus initialBoxes you start with. Each box grants candies, may contain keys for other boxes, and may contain additional boxes. Your job is to simulate opening boxes in an order that yields the maximum total candies — you can open a box only if it is unlocked or you have a key for it, and each box is opened at most once.

This problem is typically solved with a BFS-like simulation and greedy exploration. You maintain:

  • a queue (or list) of boxes you currently have access to,
  • a set of keys you possess,
  • a visited/opened set so you don't double-count boxes.

Flow/stages you should follow in an interview:

  1. Confirm the function signature and types (status, candies, keys, containedBoxes, initialBoxes → int).
  2. Initialize data structures: queue for available boxes, sets for owned keys and opened boxes.
  3. Repeatedly try to open accessible boxes: when you open one, add its candies to the total, add any new keys and contained boxes to your pool, and mark it opened. Loop until no new opens are possible.

Skill signals the interviewer looks for: correct simulation logic, handling duplicates and cycles, careful use of sets/queues, edge-case reasoning (no initial unlocked boxes, keys for already-opened boxes, nested containment), and time/space complexity analysis. Expect follow-ups about optimality, complexity, and variant constraints (e.g., limited key uses, streaming boxes).

Common Follow-up Questions

  • How would you change the algorithm if keys could be used only a limited number of times (e.g., consumable keys)?
  • Prove that the BFS/greedy simulation always yields the maximum candies. Could there be a case where exploring a different available box first increases the total?
  • How would you optimize your solution if n is very large (10^6) and memory is constrained?
  • Modify the function to return the sequence of boxes opened that achieves the maximum candies (not just the total).
  • How would you handle the variant where some boxes require multiple distinct keys to open?

Related Questions

1Keys and Rooms / graph reachability (can you visit all rooms given keys?)
2Collect maximum coins with locked cells — adapt BFS with resource constraints
3Design a system to manage nested resources and unlocking dependencies (dependency graph traversal)

Explore More Questions

Practice This Question with AI

Get real-time hints, detailed requirements, and insightful analysis of the question.

Airbnb Coding Question: Max Candies From Boxes - BFS | Voker