LeetCode: Height Checker Solution

Clone and sort

Approach

Clone new array, sort and then compare pairs

Implementation

1/**
2 * @param {number[]} heights
3 * @return {number}
4 */
5var heightChecker = function (heights) {
6 const expected = [...heights].sort((a, b) => a - b)
7 let res = 0
8
9 for (let i = 0; i < heights.length; i++) {
10 res += heights[i] !== expected[i] ? 1 : 0
11 }
12
13 return res
14}

Comments

Loading comments...

Tags

leetcode

array

sorting

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: Find Pivot Index

2 prefix sums

Previous Post

HoningJS

Search Posts