Problem 98
Squares of a Sorted Array
Easy · 10 pts · Array, Two Pointers, Sorting
Problem
You are given an array of N integers sorted in non-decreasing order; it may contain negative numbers. Square every element and print the squares, also in non-decreasing order. Squaring a negative number can make it larger than squares of positive numbers, so the squares are not automatically sorted. The largest squares come from the two ends of the array, so use two pointers at both ends, repeatedly take the larger square, and fill the result from the back. This takes O(N).
Input
First line: integer N. Second line: N integers in non-decreasing order.
Output
Print the N sorted squares, space-separated.
Constraints
1 <= N <= 100000; -10000 <= A[i] <= 10000
Example input
5 -4 -1 0 3 10
Example output
0 1 9 16 100
Explanation
Squaring -4 -1 0 3 10 gives 16 1 0 9 100. Sorted in non-decreasing order, the squares are 0 1 9 16 100.