Nesting Gift Boxes
A gift shop packs fragile orders in nested pouches, boxes and crates. The packer logs every move with one character: ( opens a pouch and ) closes it, [ and ] do the same for a box, { and } for a crate.
A log is fine only if the packer always closed the container they were working in: you cannot seal a crate while a box inside it is open. A script checks each log before the order ships.
Your task
Write packedRight(log). Return true if every container is closed by the matching kind, in the right order, with nothing left open. Otherwise return false.
A close is correct only if it matches the most recently opened container still open. Any kind may sit inside any other (a crate inside a pouch is fine); only the order of opening and closing matters. An empty log is fine: return true.
packedRight(log: string) → bool
Examples
log = "{[()]}"true
Open crate, box, pouch; then close pouch, box, crate. Each close matches the newest container still open.
log = "{[}]"false
The packer opens a crate, then a box, then closes the crate while the box is still open. Each container opens and closes once, so a count looks fine, but the order is wrong.
log = "[](()"
false
The box opens and closes. Then two pouches open and only one closes, leaving a pouch open.
Constraints
- 0 ≤ log.length ≤ 10,000
- log contains only the characters ( ) [ ] { }
Start with brute force
Repeatedly delete any adjacent matching pair, (), [] or {}, until none is left. If the string ends up empty, the log was fine.
Each pass scans the whole string and may remove only one pair: a 10,000-character log can need 5,000 passes, tens of millions of steps. A stack does it in one pass.
Hints
0 of 4 shown- Hint 1
In
{[()]}, when the packer types), which container must it close: the first opened, or the last? - Hint 2
A close always refers to the newest container still open. Once closed, the one before it is the newest open again. That is last in, first out.
- Hint 3
Counting is not enough:
([)]has one of each kind but is wrong. You must remember the order the open containers were opened in. - Hint 4
Keep a stack of open containers. On an opener, push it. On a closer, the stack must be non-empty and its top must be the matching opener; pop it. At the end, the stack must be empty.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
Every close must match the newest container still open. A stack gives you exactly "newest first": push on open, check the top on close.
Trace {[()]}:
- The characters
{,[and(are all openers, so all three are pushed. The stack is{ [ (, with(on top. - The character
)matches the top,(, so it is popped. The stack is{ [. - The character
]matches the top,[, so it is popped. The stack is{. - The character
}matches the top,{, so it is popped. The stack is empty at the end, so the function returnstrue.
In {[}], after {[ the top is [ but the next character is }, which does not match, so the function returns false at once.
Two checks are easy to forget: a close on an empty stack (] alone), and openers left on the stack at the end ((().
function packedRight(log) {
const opener = { ')': '(', ']': '[', '}': '{' };
const open = []; // containers still open, newest on top
for (const ch of log) {
if (ch === '(' || ch === '[' || ch === '{') {
open.push(ch);
} else {
// a close must match the newest open container
if (open.length === 0 || open[open.length - 1] !== opener[ch]) return false;
open.pop();
}
}
return open.length === 0; // nothing left open
}def packed_right(log):
opener = {')': '(', ']': '[', '}': '{'}
open_stack = [] # containers still open, newest on top
for ch in log:
if ch in '([{':
open_stack.append(ch)
else:
# a close must match the newest open container
if not open_stack or open_stack[-1] != opener[ch]:
return False
open_stack.pop()
return not open_stack # nothing left openRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.