You are stacking lettered blocks into a pyramid. Each row is one block shorter than the row below it, and each block rests on the two blocks right under it. Letters come from A to F.
Not every stack is allowed. allowed lists three-letter patterns: "XYZ" means a Z may sit on top of X (left) and Y (right). Order matters, so "XYZ" says nothing about Y on the left and X on the right.
Given the bottom row bottom and the list allowed, return true if you can build all the way up to a single block using only allowed patterns, or false if you cannot.
Example 1
Input: bottom = "ABC", allowed = ["ABD","ABE","BCF","EFA"] Output: true Why: the row "DF" is stuck, but "EF" can carry an A
2 more examples and the constraints
Example 2
Input: bottom = "AABB", allowed = ["AAC","ABD","BBC","CDE","DCF"] Output: false Why: the only rows are "CDC" and then "EF", and nothing fits on EF
Example 3
Input: bottom = "EF", allowed = ["FEA"] Output: false Why: the pattern needs F on the left and E on the right
Constraints
- bottom has 2 to 6 letters
- allowed holds at most 216 distinct patterns, each of 3 letters
- All letters are from A to F
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain backtrackingExponential
- Backtracking with a dead-row memo≤ 6^n rows
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work on a hard false case | Verdict |
|---|---|---|---|
| Plain backtracking | Exponential | Re-solves failed rows | |
| Backtracking with a dead-row memo | ≤ 6^n rows | Best; each row once |
n = bottom.length (at most 6), 6 = number of letters.
Edge cases to test
- No patterns. allowed = [] means no block can go anywhere: false.
- Two blocks. bottom of length 2 needs just one pattern for that exact pair.
- Pair order. "EF" with only "FEA" fails: patterns are not symmetric.
- Dead end high up. A row may build fine for a few levels and fail near the top; back up properly.
- Same row from many paths. "AAAA" with AA → B or C: eight middle rows all lead to "DD".
Common mistakes
- Treating a pattern "XYZ" as if it also allowed Y on the left and X on the right.
- Building only one candidate next row instead of trying every top for every pair.
- Memoizing rows as failed before all of their choices have been tried.
How to talk through it
- 1Clarify. Is the pattern order left-right-top? Can a pattern be used many times?
- 2Index the patterns. Map each bottom pair to its possible tops for quick lookups.
- 3Backtrack row by row. Fill the next row pair by pair, recurse when it is complete.
- 4Add the memo. A row's answer depends only on the row, so remember the ones that fail.
- 5Test out loud. Run a dead end that needs backtracking, an empty allowed list, and a reversed pair.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?