Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Two pointers

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Two pointers

Squares of a Sorted Array

beginnerlayer B4 · Two pointers5 tests

Given an integer array nums sorted in non-decreasing order, return a new array containing the square of every number, also sorted in non-decreasing order.

  • The input may contain negative numbers — that is the whole difficulty, since (-4)^2 is larger than 3^2
  • Do not mutate the input array
  • Sorting the squares afterwards is O(n log n). Aim for O(n) using two pointers

Example: [-4,-1,0,3,10] becomes [0,1,9,16,100].

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen