Skip to content

Commit 6d786d4

Browse files
committed
Squares of a sorted Array
1 parent cc707ca commit 6d786d4

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Squares_of_a_Sorted_Array.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Given an array of integers A sorted in non-decreasing order, return an
2+
# array of the squares of each number, also in sorted non-decreasing order.
3+
#
4+
# Example 1:
5+
#
6+
# Input: [-4,-1,0,3,10]
7+
# Output: [0,1,9,16,100]
8+
#
9+
# Example 2:
10+
#
11+
# Input: [-7,-3,2,3,11]
12+
# Output: [4,9,9,49,121]
13+
14+
15+
class Solution:
16+
def sortedSquares(self, A):
17+
negative_stack = []
18+
res = []
19+
20+
for num in A:
21+
if num < 0:
22+
negative_stack.append(num)
23+
continue
24+
25+
while len(negative_stack) and -negative_stack[-1] <= num:
26+
res.append(negative_stack.pop() ** 2)
27+
28+
res.append(num ** 2)
29+
30+
while len(negative_stack):
31+
res.append(negative_stack.pop() ** 2)
32+
33+
return res

0 commit comments

Comments
 (0)