awelgorithms

Distinguish nested from adjacent pairs

Updated

Adjacent: stack returns to empty between pairs. Nested: stack size stays ≥ 1 while an inner pair lives. Both can be valid. Problems that say outermost vs each pair need this distinction.

What to focus on

Max-depth > 1 implies some nesting occurred. All pairs adjacent iff max-depth is 1 (or 0).

Worked examples

nested

s = "(())"
  1. max depth 2

Result: nested

adjacent

s = "()()"
  1. max depth 1
  2. empty between

Result: adjacent

mixed

s = "()(())"
  1. a depth-1 pair then a depth-2 pair

Result: both

Try it

Write classifyPairs(s). s is a well-formed string of one bracket type. Use max depth and whether the stack emptied between pairs. "(())" nested. "()()" adjacent. "()(())" both.

s is a well-formed non-empty string of one bracket type.