Forem

ARUL SELVI ML
ARUL SELVI ML

Posted on

Squares of a Sorted Array

Squares of a Sorted Array

Problem Statement

Given a sorted array of integers in non decreasing order, return an array of the squares of each number also sorted in non decreasing order.


Examples

Input
arr = [-4, -1, 0, 3, 10]

Output
[0, 1, 9, 16, 100]


Input
arr = [-7, -3, 2, 3, 11]

Output
[4, 9, 9, 49, 121]


Approach 1 Using Sorting

Square each element and then sort the array.


Steps

1 Square all elements
2 Sort the array


Code

```python id="sq1"
def sortedSquares(arr):
result = [x * x for x in arr]
result.sort()
return result




---

## Approach 2 Two Pointer Method

Since the array is already sorted, use two pointers to build the result efficiently.

---

### Steps

1 Initialize left pointer at start and right pointer
Enter fullscreen mode Exit fullscreen mode

Top comments (0)