LeetCode: Brick Wall Solution

1/*
2 bricks: [1, 2, 2, 1]
3 edges: [1, 3, 5] (reject last one)
4 min cross brick = number of wall - maximum crossed edges
5*/
6
7/**
8 * @param {number[][]} wall
9 * @return {number}
10 */
11var leastBricks = function (wall) {
12 const edges = wall.flatMap(w => {
13 w.pop()
14 let sum = 0
15 for (let i = 0; i < w.length; i++) {
16 w[i] += w[i - 1] || 0
17 sum += w[i]
18 }
19 return w
20 })
21
22 const occurrences = Array.from(
23 edges
24 .reduce((acc, el) => acc.set(el, (acc.get(el) || 0) + 1), new Map())
25 .values()
26 )
27
28 return wall.length - Math.max.apply(null, [0, ...occurrences])
29}

Comments

Loading comments...

Tags

leetcode

hash table

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

LeetCode: Count Binary Substrings

Previous Post

LeetCode: Triangle

Memoized recursion

HoningJS

Search Posts