20. Valid Parentheses
Asked at 90Bloomberg83Meta76Amazon74Microsoft72Apple70Google67Tripadvisor100Intuit100Walmart Labs95BlackRock91Siemens88Epic Systems84IBM83LinkedIn79tcs75Virtu Financial64Accolite64Chewy100FreshWorks100Odoo100Zenefits100X94Bank of America93Zoho92HP91USAA89Intel88Nokia87Ozon87Mastercard86VK84Autodesk82HCL81SAP81EPAM Systems80Deloitte78Nvidia78Lucid78Huawei76Qualcomm76GoDaddy76Toast76Rokt75Adobe74Oracle74Comcast74Cognizant73ServiceNow73Spotify73Visa72Turing71Sony70Criteo69UBS69persistent systems69Altimetrik69AMD69Tesla68Infosys68Publicis Sapient68opentext67Two Sigma67Airbnb66Grab66Wells Fargo65CrowdStrike65Expedia65PhonePe64eBay64Wipro63Roblox62Yahoo61Yandex59Jane Street59TikTok58Dell57MathWorks56Cisco56DE Shaw53Barclays53Wix52PayPal51Booking.com50Palo Alto Networks50Agoda48Flipkart43Anduril41Goldman Sachs40Salesforce35Uber22
Problem
s contains only the brackets ()[]{}. Decide whether it is valid: every opening bracket is closed by the same type of bracket, in the correct (properly nested) order.
Example: "()[]{}" → true; "(]" → false; "([)]" → false
Push expected closers; on a closer, it must match the top.
Complexity: O(n).
class Solution:
def isValid(self, s: str) -> bool:
pair = {")": "(", "]": "[", "}": "{"}
st = []
for ch in s:
if ch in pair:
if not st or st.pop() != pair[ch]:
return False
else:
st.append(ch)
return not st
assert Solution().isValid("()[]{}") is True
assert Solution().isValid("(]") is False
assert Solution().isValid("([)]") is False
assert Solution().isValid("{[]}") is True
class Solution {
public boolean isValid(String s) {
Deque<Character> st = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') st.push(')');
else if (c == '[') st.push(']');
else if (c == '{') st.push('}');
else if (st.isEmpty() || st.pop() != c) return false;
}
return st.isEmpty();
}
}
func isValid(s string) bool {
pair := map[byte]byte{')': '(', ']': '[', '}': '{'}
st := []byte{}
for i := 0; i < len(s); i++ {
if open, ok := pair[s[i]]; ok {
if len(st) == 0 || st[len(st)-1] != open {
return false
}
st = st[:len(st)-1]
} else {
st = append(st, s[i])
}
}
return len(st) == 0
}