# LeetCode: Squares of a Sorted Array Solution

Map and sort or vice versa

## Implementation: Array Manipulation

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var 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 ** 23
4  const n = nums.length5  let lo = 06  let hi = n - 17  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}```

leetcode

array

two pointers

## Next Post

LeetCode: Max Consecutive Ones

Jan 31, 2021

## Previous Post

Codility: MaxNonoverlappingSegments

Jan 30, 2021

Lesson 16 Greedy Algorithms

Search Posts