Hackerrank: Balanced Brackets Solution

1function Stack() {
2 const stack = []
3
4 this.push = function (el) {
5 stack.push(el)
6 }
7
8 this.pop = function () {
9 return stack.pop()
10 }
11
12 this.peek = function () {
13 return stack[stack.length - 1]
14 }
15
16 this.isEmpty = function () {
17 return stack.length === 0
18 }
19}
20
21function 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 }
39
40 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.

Next Post

Hackerrank: Alternating Characters

Jan 28, 2021

HoningJS

Search Posts