Hackerrank: Balanced Brackets Solution
1function Stack() {2 const stack = []34 this.push = function (el) {5 stack.push(el)6 }78 this.pop = function () {9 return stack.pop()10 }1112 this.peek = function () {13 return stack[stack.length - 1]14 }1516 this.isEmpty = function () {17 return stack.length === 018 }19}2021function isBalanced(s) {22 const isOpen = c => "{[(".includes(c)23 const closeOf = c =>24 ({25 "{": "}",26 "[": "]",27 "(": ")",28 }[c])29 const stack = new Stack()30 for (const c of s) {31 if (isOpen(c)) {32 stack.push(c)33 } else if (c === closeOf(stack.peek())) {34 stack.pop()35 } else {36 stack.push(c)37 }38 }3940 return stack.isEmpty() ? "YES" : "NO"41}
Comments
Loading comments...
Tags
hackerrank
stack
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.