Benchmark of squares of a sorted array in Python: sorted() 4.68 ms, two pointers 9.67 ms, deque 10.42 ms, insert(0) 818.92 ms

Squares of a sorted array looks like a five-minute problem. Most people write a one-line answer, get asked for something faster, and reach for two pointers. The two-pointer version has a trap in it, though: one of the easiest ways to write it says “linear time” on the tin and runs in quadratic time. On a list of 100,000 numbers it is about 170 times slower than the one-liner.

In this post I cover the squares of a sorted array problem properly: the obvious solution, the two-pointer solution interviewers expect, the bug that makes it quadratic, and a benchmark with a result I did not expect. The fastest version in Python is not the O(n) one.


The squares of a sorted array problem

You get a list of integers sorted in ascending order. Return the squares of each number, also sorted in ascending order. It is LeetCode problem 977 and a common warm-up question in interviews.

Input:  [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]

The catch is the negative numbers. The input is sorted, but squaring flips the order of the negative part: -4 is the smallest input but 16 is not the smallest square. So you cannot square each number in place and be done.

Solution 1: square, then sort

The first answer almost everyone writes is one line:

def squares_sort(nums):
    return sorted(x * x for x in nums)

It is correct and easy to read. Sorting is O(n log n), so in an interview this is where the follow-up question comes: can you do it in O(n)?

Solution 2: two pointers

The largest square must come from one of the two ends of the list: either the most negative number on the left or the largest number on the right. So you put one pointer at each end, compare the absolute values, take the bigger square, and move that pointer inwards. Each step finds the next largest square, so you fill the answer from the back.

That is the whole idea. The details are where it goes wrong.

The bug that makes it quadratic

Here is a version that is easy to write and looks correct:

def squares_insert_front(nums):
    left, right = 0, len(nums) - 1
    result = []
    while left <= right:
        if abs(nums[left]) > abs(nums[right]):
            result.insert(0, nums[left] ** 2)
            left += 1
        else:
            result.insert(0, nums[right] ** 2)
            right -= 1
    return result

It gives the right answer. The problem is result.insert(0, ...). A Python list is an array in memory, so inserting at the front has to shift every element already in the list one place to the right. The first insert moves nothing, the second moves one item, the last moves n−1. Added up, that is about n²/2 moves. The loop is linear; the list operations inside it are not.

The loop was linear. The list operations inside it were not.

There are two simple fixes. You can create the result list at full size and write into it from the back, or you can use collections.deque, whose appendleft is O(1). Here are all four versions in one file:

from collections import deque


def squares_sort(nums):
    """Square everything, then sort. O(n log n), and the easiest to read."""
    return sorted(x * x for x in nums)


def squares_insert_front(nums):
    """Two pointers, but insert(0, ...) shifts the whole list every time."""
    left, right = 0, len(nums) - 1
    result = []
    while left <= right:
        if abs(nums[left]) > abs(nums[right]):
            result.insert(0, nums[left] ** 2)
            left += 1
        else:
            result.insert(0, nums[right] ** 2)
            right -= 1
    return result


def squares_two_pointer(nums):
    """Two pointers, filling a pre-sized list from the back. O(n)."""
    n = len(nums)
    result = [0] * n
    left, right = 0, n - 1
    for pos in range(n - 1, -1, -1):
        if abs(nums[left]) > abs(nums[right]):
            result[pos] = nums[left] * nums[left]
            left += 1
        else:
            result[pos] = nums[right] * nums[right]
            right -= 1
    return result


def squares_deque(nums):
    """Same idea with deque.appendleft, which is O(1)."""
    left, right = 0, len(nums) - 1
    result = deque()
    while left <= right:
        if abs(nums[left]) > abs(nums[right]):
            result.appendleft(nums[left] * nums[left])
            left += 1
        else:
            result.appendleft(nums[right] * nums[right])
            right -= 1
    return list(result)

Testing four solutions to squares of a sorted array

Before timing anything, I wanted to be sure all four give the same answers, including the edge cases: an empty list, one item, all negatives, and duplicates. The second test compares each function with the one-line version on 500 random sorted lists.

import random

import pytest

from squares import (squares_deque, squares_insert_front, squares_sort,
                     squares_two_pointer)

ALL = [squares_sort, squares_insert_front, squares_two_pointer, squares_deque]


@pytest.mark.parametrize("fn", ALL)
@pytest.mark.parametrize("nums, expected", [
    ([-4, -1, 0, 3, 10], [0, 1, 9, 16, 100]),
    ([-7, -3, 2, 3, 11], [4, 9, 9, 49, 121]),
    ([], []),
    ([5], [25]),
    ([-5, -3, -1], [1, 9, 25]),
    ([-2, -2, 2, 2], [4, 4, 4, 4]),
])
def test_known_cases(fn, nums, expected):
    assert fn(nums) == expected


@pytest.mark.parametrize("fn", ALL)
def test_matches_sorted_on_random_input(fn):
    rng = random.Random(42)
    for _ in range(500):
        nums = sorted(rng.randint(-1000, 1000) for _ in range(rng.randint(0, 50)))
        assert fn(nums) == sorted(x * x for x in nums)
$ python -m pytest -q
............................                                             [100%]
28 passed in 0.04s

Squares of a sorted array, benchmarked: the O(n) answer loses

I timed each function with timeit on sorted lists of random integers between −1,000,000 and 1,000,000, taking the best of five runs. This was Python 3.12 on an Apple M2 Pro.

List sizesorted()Two pointers (pre-sized list)Two pointers (deque)Two pointers (insert(0))
1,0000.05 ms0.09 ms0.11 ms0.17 ms
10,0000.43 ms0.93 ms1.01 ms7.04 ms
100,0004.68 ms9.67 ms10.42 ms818.92 ms

Two things stand out. First, the insert(0) version falls apart as the list grows. Ten times more data makes it about a hundred times slower, which is exactly what quadratic growth looks like. At 100,000 items it takes most of a second.

Second, and this surprised me: the one-line sorted() version, the one that is supposed to be O(n log n), is about twice as fast as the correct O(n) two-pointer versions at every size.

Why sorted() wins in Python

There are two reasons. The first is plain: sorted() runs in C, while the two-pointer loop runs one Python bytecode step at a time. Each comparison, index and assignment in the loop costs far more than the same work inside the sort.

The second reason is more interesting. Python’s sort looks for runs, stretches of data that are already in order, and merges them instead of sorting from scratch. Squaring a sorted list gives you exactly two runs: the squares of the negative numbers, which fall, and the squares of the rest, which rise. The sort reverses the falling run and merges the two. On this input it does close to linear work.

I checked this by sorting a million squares twice: once in the order squaring produces, and once shuffled.

sorted() on squares of sorted input          9.2 ms
sorted() on same values shuffled            42.9 ms

Same values, same function, more than four times faster, because the data already had structure the sort could use. The O(n log n) label describes the worst case. It does not describe this input.

So which answer should you give?

When squares of a sorted array comes up in an interview, give both answers. Start with sorted(), say it is O(n log n), then write the two-pointer version and explain why it is O(n). If you write the two-pointer version, fill a pre-sized list from the back. Do not insert at the front of a list; that turns your O(n) answer into an O(n²) one, and a good interviewer will notice.

Then, if there is time, mention the benchmark. Saying that sorted() is likely faster in CPython for this input, and why, shows you know the difference between complexity and speed. That is a better signal than the algorithm alone.

In real code, use sorted(). It is shorter, it is harder to get wrong, and on this problem it is faster.

And if your numbers are already in NumPy

All of this assumes a plain Python list. If your data lives in a NumPy array, for example because it came out of pandas or a file of measurements, the answer changes again. Squaring and sorting both happen inside compiled code, on the whole array at once:

import numpy as np

arr = np.array(nums, dtype=np.int64)
result = np.sort(arr * arr)

I timed it on a million numbers, against the two best list versions. The NumPy result is checked against the sorted() result in the script, so all three give the same answer.

sorted() on a list              48.4 ms
two pointers on a list         101.5 ms
np.sort(a * a) on an array       0.6 ms

That is about eighty times faster than sorted(). The lesson is the same one again, just bigger: where the work runs matters more than the algorithm on paper. One caution: int64 squares overflow silently above about three billion, so check the range of your values before you square them in NumPy. Python integers never overflow.

Where the two-pointer idea still earns its place

None of this makes the two-pointer technique useless. In C, Java, Go or Rust there is no slow interpreter loop to pay for, so the O(n) version does what the textbook says and beats a general sort on large inputs. It is also the same move as the merge step in merge sort: two sorted sequences, one pointer each, always take the better head. Once you see it here, you will recognise it in merging sorted files, joining sorted lists of timestamps, and in the run merging that makes Python’s own sort fast on this problem.

So learn it, and be able to write it correctly. Just do not assume it is the fastest choice in every language.

The general lesson

Big-O tells you how cost grows as input grows. It hides the constant factor, and in Python the constant factor between a C function and a Python loop is large. When performance matters, measure. When you write a “linear” algorithm, check every operation inside the loop, not just the loop. The insert(0) version above passes every test and still breaks the one promise it makes.

If you are newer to Python and want the basics behind lists, loops and functions used here, my Python beginner guide covers them. For what is changing in the language itself, see Python 3.15 features developers should know.

Further reading

Leave A comment

Are you human? Please solve:Captcha