Squares of a Sorted Array - Array - Easy - LeetCode
💻 coding

Squares of a Sorted Array - Array - Easy - LeetCode

1 min read 123 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires returning the squares of a sorted array in non-decreasing order.
  • 2The solution uses a stack to handle negative numbers and an array for non-negative squares.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires returning the squares of a sorted array in non-decreasing order."

Squares of a Sorted Array - Array - Easy - LeetCode

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

Example 1:

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

Input: [-7,-3,2,3,11] Output: [4,9,9,49,121]

Note:

1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order.

public class Solution {
 public int[] SortedSquares(int[] A) {
 var stack = new Stack<int>(); 
 var pos = new int[A.Length];
 var posLen = 0;
 int i = 0;
 for(i=0;i<A.Length;i++){
 if(A[i]<0){
 stack.Push(A[i]*A[i]);
 }
 else{
 pos[posLen]=A[i]*A[i];
 posLen++;
 }
 }
 
 i=0;
 int j=0;
 while(stack.Count>0){
 if(posLen==0 || j>=posLen){
 A[i]=stack.Pop();
 }
 else if(stack.Peek()<pos[j]){
 A[i]=stack.Pop();
 }
 else{
 A[i]=pos[j];
 j++;
 }
 i++;
 }
 
 while(j<posLen){
 A[i]=pos[j];
 j++;
 i++;
 }
 
 return A;
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 27 September 2020 · 1 min read · 123 words

Part of AskGif Blog · coding

You might also like