Squares of a Sorted Array

Squares of a Sorted Array is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the Converging (Sorted Array Target Sum) subpattern.

Problem statement

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]

Constraints:

- 1 <= nums.length <= 104

- -104 <= nums[i] <= 104

- nums is sorted in non-decreasing order.

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

Topics and companies

Topics: Array, Two Pointers, Sorting.

Reported in interviews at Facebook, Uber, Google, Amazon, Apple, Bloomberg, Yandex, Microsoft, ByteDance, Flipkart, Cisco.

How to practise Squares of a Sorted Array on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(1) space.

Open Squares of a Sorted Array in the code editor, or read the Squares of a Sorted Array editorial for a worked solution with its approach and complexity analysis.

Where Squares of a Sorted Array sits in the DSA pattern sheet

Problems related to Squares of a Sorted Array

Other problems that use the same Converging (Sorted Array Target Sum) and Two Pointers techniques:

Opening the problem

Progress is saved as you study.