Squares of a Sorted Array
Problem Statement
You are given an integer array nums sorted from smallest to largest. It can contain negative numbers.
Return a new array with the square of every number, also sorted from smallest to largest.
Follow-up: squaring and then sorting is easy. Can you do it in O(n) time?
An integer array nums, sorted in non-decreasing order.
An array of the squares of nums, sorted in non-decreasing order.
The squares are [16, 1, 0, 9, 100]. Sorted, that's [0, 1, 9, 16, 100].
The squares are [49, 9, 4, 9, 121]. Sorted, that's [4, 9, 9, 49, 121].
- β’ 1 β€ nums.length β€ 10^4
- β’ β10^4 β€ nums[i] β€ 10^4
- β’ nums is sorted in non-decreasing order
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Square every number, then sort the result
Bigger square of the two ends goes into the last empty slot
Square each number into a new array, then sort it.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.