LeetCode: Squares of a Sorted Array Solution

Map and sort or vice versa

Implementation: Array Manipulation

1var sortedSquares = function (nums) {
2 return nums.map(num => num * num).sort((a, b) => a - b)
3}

Implementation: Two Pointers

1var sortedSquares = function (nums) {
2 const powOf2 = x => x ** 2
3
4 const n = nums.length
5 let lo = 0
6 let hi = n - 1
7 const res = []
8
9 while (lo <= hi) {
10 const a = powOf2(nums[lo])
11 const b = powOf2(nums[hi])
12 if (a < b) {
13 res.push(b)
14 hi--
15 } else {
16 res.push(a)
17 lo++
18 }
19 }
20
21 return res.reverse()
22}

Comments

Loading comments...

Tags

leetcode

array

two pointers

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: Max Consecutive Ones

Previous Post

Codility: MaxNonoverlappingSegments

Lesson 16 Greedy Algorithms

HoningJS

Search Posts