Codility: StoneWall Solution

Lesson 7 Stacks and Queues

Implementation

1function Stack() {
2 stack = []
3
4 this.push = function (el) {
5 stack.push(el)
6 }
7
8 this.pop = function () {
9 return stack.pop()
10 }
11
12 return {
13 ...this,
14 get size() {
15 return stack.length
16 },
17 get head() {
18 return stack[this.size - 1]
19 },
20 }
21}
22
23function solution(H) {
24 let stack = new Stack()
25 let count = 0
26 H.forEach(h => {
27 while (stack.size && stack.head > h) {
28 stack.pop()
29 }
30 if (stack.size && stack.head === h) {
31 return
32 }
33 stack.push(h)
34 count++
35 })
36 return count
37}

References

https://codility.com/media/train/solution-stone-wall.pdf

Comments

Loading comments...

Tags

codility

Next Post

Codility: Nesting

Jan 23, 2021

Lesson 7 Stacks and Queues

Previous Post

Codility: Distinct

Jan 22, 2021

Lesson 6 Sorting

HoningJS

Search Posts