Nesting Gift Boxes

EasystackAlso known as Valid Parentheses

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

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

Open crate, box, pouch; then close pouch, box, crate. Each close matches the newest container still open.

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

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.

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

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

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