FastPrepBalanced Parentheses Inside a String

Balanced Parentheses Inside a String

Capital One logoCapital One● EasyINTERNNEW GRADFULLTIMEONSITE INTERVIEW

Updated

Problem statement

The string s holds letters, digits and round parentheses. Ignore everything except the parentheses. Return true if every ( can be paired with a later ) and every ) with an earlier (, with pairs nested or side by side but never crossing. Otherwise return false.

A string with no parentheses is balanced.

Function

isBalanced(s: String) → boolean

Examples

Example 1

s = "ab(c(d)e)f"return = true

Letters are ignored. The inner (d) closes first, then the outer pair closes around it, so every parenthesis has a partner.

Example 2

s = "((x)"return = false

Two parentheses open but only one closes, so one is left without a partner.

Example 3

s = "1)(2"return = false

There is one of each, but the ) comes first, when nothing is open yet, so it cannot be matched.

Example 4

s = "abc"return = true

With no parentheses at all there is nothing to match, so the string counts as balanced.

Constraints

  • 1 <= s.length <= 10^5
  • s contains only English letters, digits, ( and ).

More Capital One Onsite Interview questions

Similar questions at other companies

Capital One interview experiences

All Capital One interview questionsSee Capital One hiring insights
Saved
class Solution {
    public boolean isBalanced(String s) {
        // Write your code here.
    }
}
Checking account…