Codility: Fish Solution

Lesson 7 Stacks and Queues
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(A, B) {
24 const stack = new Stack()
25 for (let i = 0; i < A.length; i++) {
26 let curr = { A: A[i], B: B[i] }
27 if (!stack.head) {
28 stack.push(curr)
29 continue
30 }
31
32 if (stack.head.B === 1 && curr.B === 0) {
33 let head
34 while (1) {
35 head = stack.pop()
36 const winner = head.A > curr.A ? head : curr
37 curr = winner
38 if (!(stack.head && stack.head.B === 1 && curr.B === 0)) {
39 stack.push(winner)
40 break
41 }
42 }
43 } else {
44 stack.push(curr)
45 }
46 }
47 return stack.size
48}

Comments

Loading comments...

Tags

codility

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

Codility: Brackets

Lesson 7 Stacks and Queues

Previous Post

Codility: Nesting

Lesson 7 Stacks and Queues

HoningJS

Search Posts