Let's now get into the code for the second approach that we have discussed for solving the sorted squared
array question.
Okay.
So we are going to start by creating a new array.
So let me say const new array is equal to new array.
And this new array will have the same size as the input array which is what is given us over here.
Okay.
So over here and say array dot length.
And what we're going to do is we're going to fill every cell in the new array with the value zero.
So over here I'll say dot fill zero.
Okay.
Now we have seen that the highest value will either be the squared of the leftmost element or the rightmost
element in the array, which is given to us.
So let's have two pointers.
So I'll say let pointer left.
Is equal to zero, which is the left most index.
And also I'll say let pointer right.
Is equal to array dot length minus one.
Okay, now I'm going to iterate over every index in the new array which we have created over here.
But we will start at the last index and go up to zero.
So over here I'll say for let I is equal to array dot length minus one and I greater than equal to zero.
Because we will be going till I equal to zero and I minus minus.
Okay.
Now we will find the squared value of the leftmost element and the rightmost element.
So I'll say const left squared.
Is equal to math dot pow array at pointer left okay.
And we are squaring it.
So comma two over here.
And similarly const right squared.
Is equal to math dot pow array.
At point or write.
And again comma two okay.
Because we are squaring it.
Now we are going to compare these two values.
So I will say if left squared greater than right squared.
So if this is the case then we will say new array at index I is equal to left squared.
And because we have used up the left squared or the element at which the left pointer is pointing at
the current moment, we are going to change that pointer by incrementing it.
So I will say pointer left plus plus okay.
Now if this is not the case.
What we are going to do is we'll say new array at index I is equal to write squared okay.
And then because we have used the element at which the right pointer was pointing, we are going to
shift the right pointer by decrementing it.
So I will say pointer right minus minus okay.
So that's it.
So this should solve the question.
Now all that remains is we'll have to return the new array.
So here we'll say return new array.
And that's it.
Now let's go ahead and run this code and see if it's passing all the test cases.
And you can see that it's passing all the test cases.
And again do make use of the user logs.
So for every test case you can see the input, the expected output and the actual output.
When you take a look at the user logs for each individual test case.
Also do make use of this.
If you want to debug your code, you can just have console log statements and you can print various
things which will help you debug your code in case you're stuck.