javascript
Parenthesis Validation, Max Depth and Max Breadth - Braze - Full Stack - 12/20/21
// inputStr: May or may not contain paraentheses
// valid: (()), check if valid expression
// some string // true
// (some string) // true
// ((some) string // false
// (() ())
// )))
// valid if no unbalanced set of parentheses
function hasValidParens(inputStr) {
const parens = [];
for (let i = 0; i < inputStr.split('').length; i++) {
if (inputStr[i] === '(') {
parens.push('(')
} else if (inputStr[i] === ')') {
const lastParens = parens.pop()
if (typeof lastParens == 'undefined') {
return false;
}
}
}
return parens.length === 0;
}
//console.log(hasValidParens("()")); // true
//console.log(hasValidParens("some string")); // true
//console.log(hasValidParens("(some string)")); // true
//console.log(hasValidParens("((some) string")); // false
//console.log(hasValidParens("(() ())")); // true
//console.log(hasValidParens(")))")); // false
//console.log(hasValidParens("(((")); // false
// maxDepth: (()) 2
// ((), ()) 2
// ((), (())) 3
// Assume that it's valid
function maxDepth(inputStr) {
const parens = [];
let maxDepth = 0;
for (let i = 0; i < inputStr.split('').length; i++) {
if (inputStr[i] === '(') {
parens.push('(')
} else if (inputStr[i] === ')') {
if (parens.length > maxDepth) {
maxDepth = parens.length;
}
parens.pop()
}
}
return maxDepth;
}
//console.log(maxDepth("(())")); // 1
//console.log(maxDepth("((), ())")); // 2
//console.log(maxDepth("((), (()))")); // 2
//console.log(maxDepth("((()), ())")); // 2
// ()()(()()) // 3
// maxBreadth
function maxBreadth(inputStr) {
const parens = [];
let maxBreadth = 0;
for (let i = 0; i < inputStr.split('').length; i++) {
if (inputStr[i] === '(') {
parens.push('(')
} else if (inputStr[i] === ')') {
parens.pop();
if (parens.length === 0) {
maxBreadth++;
}
}
}
return maxBreadth;
}
console.log(maxBreadth("(())")); // 1
console.log(maxBreadth("((), ())")); // 2
console.log(maxBreadth("((), (()))")); // 2
console.log(maxBreadth("((()), ())")); // 2
console.log(maxBreadth("()()(()())")); // 3
Was this helpful?
Similar Posts
- Search and Display Charities - Free Will - Nonprofit Gifts - Full Stack - 12/8/21
- LRU Cache - Alphasights - Search and Discovery - Full Stack - 12/15/21
- Lodash - Flatten an array to a fixed depth
- Van Ecks Sequence - Bloomberg - Asset Management AIM - Full Stack - 11/5/21
- 2D Array Path - C3 AI - CRM - Full Stack - 11/11/21
- Compressed String with Sort - C3 AI - CRM - Full Stack - 11/11/21
- Recommendations - Bloomberg - Port Interactive Analytics - Full Stack - 11/8/21