Squaring A Sorted Array In Python

Posted on Sep 28, 2020

Given a sorted list of integers, square the elements and give the output in sorted order.

Let's take a look at a very straightforward solution first:

def SortedSquares (arr):
     # We will use list comprehension to square our list
     temp = [x**2 for x in arr]

     # Now that we have our list squared we can use the sorted function to return our answer

     return sorted(temp)

While this solution is correct, it takes up additional space because the sorted function makes a copy of our original list.  This could be mitigated by using the sort function, but beware, make sure that the original list will not be needed as the sort() function mutates the list.  Additionally, this solution is relatively slow.  We need to go through every element in the list when we square the list and then we take 0 (log n) time to sort (Python does do a good job in the internal sorting algorithms for us).  Can we modify the solution to make it faster?  Yes!

def SortedSquares (arr):
     # since we know the list is sorted we can simply look at the first and last elements magnitude to know which square will be larger

     # let's start with two pointers, one at element [0] and one  at element [arr_length - 1]

     left, right = 0, len(arr)-1
     # we'll need to keep track of how many elements we've sorted so we'll initialize a tracker.  We also initialize an result list to store our answer

     tracker = len(arr) - 1
     final = [0 for x in arr]

     # we now move from out to in storing the largest elements first and ending with the smallest, all while squaring our result

     while index >= 0: 
        if abs(arr[left]) >= abs(arr[right]): 
            final[tracker] = arr[left] ** 2 
            left += 1
            final[tracker] = arr[right] ** 2 
            right -= 1
        tracker -= 1
    return final 


Our new solution takes up the same auxiliary space, O(n), but we now have a solution that runs in O(n) time!  Do you have another solution?  Could you rewrite this solution with no need for auxiliary space?  Post it below!

About Author

Related Articles

Leave a Comment

No comments found.

View Posts by Categories

Our Recent Popular Posts

View Posts by Tags

#python #trainwithnycdsa 2019 airbnb Alex Baransky alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus API Application artist aws beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep Bundles California Cancer Research capstone Career Career Day citibike clustering Coding Course Demo Course Report D3.js data Data Analyst data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization Deep Learning Demo Day Discount dplyr employer networking feature engineering Finance Financial Data Science Flask gbm Get Hired ggplot2 googleVis Hadoop higgs boson Hiring hiring partner events Hiring Partners Industry Experts Instructor Blog Instructor Interview Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter lasso regression Lead Data Scienctist Lead Data Scientist leaflet linear regression Logistic Regression machine learning Maps matplotlib Medical Research Meet the team meetup Networking neural network Neural networks New Courses nlp NYC NYC Data Science nyc data science academy NYC Open Data NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time Portfolio Development prediction Prework Programming PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn Selenium sentiment analysis Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau team TensorFlow Testimonial tf-idf Top Data Science Bootcamp twitter visualization web scraping Weekend Course What to expect word cloud word2vec XGBoost yelp