Nesting Gift Boxes

EasystackAlso known as Valid Parentheses

A gift shop packs fragile orders inside layers of packaging: pouches, boxes and crates, nested inside each other in whatever way fits the order. 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 still open. Before an order ships, a script checks the log.

Your task

Write packedRight(log). Return true if every container in the log is closed by the matching kind, in the right order, and nothing is left open. Otherwise return false.

A close is correct only if it matches the most recently opened container that is still open. Any kind may sit inside any other kind (a crate inside a pouch is fine); only the order of opening and closing matters. An empty log is fine (nothing was packed), so return true.

packedRight(log: string) → bool

Examples

Example 1
Input
log = "{[()]}"
Output
true
Why

Open crate, open box, open pouch. Then close the pouch, the box and the crate. Each close matches the newest container still open, so the log is fine.

Example 2
Input
log = "{[}]"
Output
false
Why

The packer opens a crate, then a box, then tries to close the crate while the box inside it is still open. Every container is opened and closed once, so a simple count looks fine, but the order is wrong.

Example 3
Input
log = "[](()"
Output
false
Why

The box opens and closes. Then two pouches open and only one closes. A pouch is left open, so the log is not fine.

Constraints

  • 0 ≤ log.length ≤ 10,000
  • log contains only the characters ( ) [ ] { }
Start with brute force

Repeatedly delete any adjacent matching pair, (), [] or {}, until no pair is left. If the string ends up empty, the log was fine.

It works, but each pass scans the whole string and may remove only one pair. A log of 10,000 characters can need 5,000 passes over thousands of characters each: tens of millions of steps. A stack does it in one pass.

Hints

0 of 4 shown

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.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code