DSA AnimatorREVISION VIDEOS
← Back to problems
New

Squares of a Sorted Array — LeetCode 977 video explanation

Given an array sorted in increasing order, which may include negative numbers, return the squares of every number, also sorted in increasing order.

Loading videos…

DSA Animator › DSA Revision › Arrays › Squares of a Sorted Array

Key moments in the Squares of a Sorted Array video

0:04Problem0:14Example0:21Brute force0:30Key idea0:44Dry run1:08Code1:22Takeaway

What you will learn

Remember: in a sorted array with negatives, the largest squares sit at the two ends. Fill the result from the back with two pointers. The video solves Squares of a Sorted Array (LeetCode 977, Easy) with the Two Pointers pattern from the Arrays topic, and you can replay every step in the interactive Squares of a Sorted Array animation.

Squares of a Sorted Array video transcript

Problem

Given an array sorted in increasing order, which may include negative numbers, return the squares of every number, also sorted in increasing order.

Example

For minus 4, minus 1, 0, 3 and 10, the squares sorted are 0, 1, 9, 16, 100.

Brute force

Squaring everything and then sorting costs O of n log n. Negative numbers break the order: minus 4 squared is bigger than 3 squared.

Key idea

The biggest square always comes from one of the two ends, because those have the largest absolute values. So use two pointers at both ends, and fill the answer from the back. Each time, place the bigger square, and move that pointer inward.

Dry run

Compare minus 4 and 10: 10 squared, 100, is bigger, so it goes last. Compare minus 4 and 3: 16 is bigger than 9, so 16 goes next. Compare minus 1 and 3: 9 is bigger, so 9 goes in. Compare minus 1 and 0: 1 is bigger, so 1 goes in. Only 0 is left, and it takes the first slot. The answer is 0, 1, 9, 16, 100.

Code

In code, put left at 0, right at the end, and fill position p from the back. Compare the absolute values at both ends. Write the larger square at p, and move that pointer inward. One pass, so it's O of n time, and O of n for the answer.

Takeaway

Remember: in a sorted array with negatives, the largest squares sit at the two ends. Fill the result from the back with two pointers.

More Arrays revision videos

← All 185 DSA revision videos