KatInterview

Leftover Brackets After Pairing Up a Parenthesis String

Stacks & QueuesAuto-graded · 22 test cases
EasyAuto-gradedStacks & Queuesstackgreedystrings

Last updated

Count the parentheses left over after forming the maximum number of valid "(" before ")" pairs, testing a greedy counter scan or stack over a string.

Leftover Brackets

You are given a string s made up only of the characters ( and ).

Form as many disjoint pairs as possible, where each pair consists of one ( and one ) that appears later in the string. Each character may belong to at most one pair.

Return the number of characters that end up in no pair.

Details

  • The order matters. A ) can only be paired with a ( that appears to its left.
  • An empty string has no leftover characters, so the answer is 0.
  • The answer is the same regardless of which maximum pairing you choose.

Function

Implement count_leftover(s), which takes the string s and returns an integer: the number of characters not belonging to any pair in a maximum pairing.

Constraints

  • 0 <= len(s) <= 10^5
  • s contains only the characters ( and ).

Examples

Example 1

Input: count_leftover('()()')

Output: 0

Example 2

Input: count_leftover('((()')

Output: 2

Example 3

Input: count_leftover(')()(')

Output: 2

Example 4

Input: count_leftover('(()(())')

Output: 1

Hints

Hint 1

Think about what you need to remember while scanning left to right: does it matter which '(' is still waiting, or only how many?

Hint 2

When you see a ')' and nothing is waiting, it can never be paired later, because only a '(' to its left could have matched it. Count it as leftover right away.

Hint 3

At the end, any '(' still waiting has no closer after it. The answer is the waiting count plus the number of ')' that arrived with nothing waiting. Comparing total counts of '(' and ')' alone fails on inputs like ')('.