← Two Pointers

Squares of Sorted Array

Easy
Python
def sorted_squares(nums):
    n=len(nums); res=[0]*n; l,r=0,n-1
    for i in range(n-1,-1,-1):
        if abs(nums[l])>abs(nums[r]):
            res[i]=nums[l]**2; l+=1
        else:
            res[i]=nums[r]**2; r-=1
    return res
Java
public int[] sortedSquares(int[] nums){
    int n=nums.length; int[] res=new int[n];
    int l=0,r=n-1;
    for(int i=n-1;i>=0;i--){
        if(Math.abs(nums[l])>Math.abs(nums[r])){
            res[i]=nums[l]*nums[l]; l++;
        } else {
            res[i]=nums[r]*nums[r]; r--;
        }
    } return res;
}

Key Insight

Fill from back. Python ** vs Java explicit multiplication.

Python → Java Differences

  • Python ** vs a*a
  • abs() vs Math.abs()
  • Fill from back identical
Python
def sorted_squares(nums):
    n=len(nums); res=[0]*n; l,r=0,n-1
    for i in range(n-1,-1,-1):
        if abs(nums[l])>abs(nums[r]):
            res[i]=nums[l]**2; l+=1
        else:
            res[i]=nums[r]**2; r-=1
    return res
Java
public int[] sortedSquares(int[] nums){
    int n=nums.length; int[] res=new int[n];
    int l=0,r=n-1;
    for(int i=n-1;i>=0;i--){
        if(Math.abs(nums[l])>Math.abs(nums[r])){
            res[i]=nums[l]*nums[l]; l++;
        } else {
            res[i]=nums[r]*nums[r]; r--;
        }
    } return res;
}

Algorithm Steps

1. Two pointers from ends
2. Fill result from back
3. Larger square at end