↓Skip to main content
  1. LeetCode/

LeetCode 977: Squares of a Sorted Array

·1 min· ·
LeetCode Easy Array Two-Pointers Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-26

  • Submissions: Wrong Answer → Accepted ×3

Approach
#

Negatives scramble the order after squaring, but the largest square is always at one of the ends (Two Pointers Template 1). Compare the squares at both ends and place the larger at the back of the result, moving inward.

My Attempts
#

Attempt 1 wrote [...].sort(); sort() works in place and returns None, so the function returned None.

Solution
#

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        n = len(nums)
        res = [0] * n
        l, r = 0, n - 1
        for k in range(n - 1, -1, -1):
            if abs(nums[l]) > abs(nums[r]):
                res[k] = nums[l] * nums[l]
                l += 1
            else:
                res[k] = nums[r] * nums[r]
                r -= 1
        return res

Complexity
#

Time O(n), space O(n) for the output.

Mistakes to Avoid
#

  • list.sort() sorts in place and returns None; use sorted() to get a list back.

Interview Explanation
#

The largest square sits at an end, so two pointers compare absolute values and write the larger square from the back of the result. Time O(n).

Related

LeetCode 905: Sort Array By Parity
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 905 note: a write pointer swaps even numbers to the front, just like move zeroes
LeetCode 922: Sort Array By Parity II
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 922 note: pointers i over even slots and j over odd slots, each stepping by two; when slot i holds an odd number, move j to a misplaced even and swap
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 888: Fair Candy Swap
·2 mins
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 note: equal sums after swapping x and y means y = x + (sumB - sumA) / 2; put B in a set and check each x from A
LeetCode 821: Shortest Distance to a Character
·2 mins
LeetCode Easy Array Two-Pointers String
LeetCode 821 note: one left-to-right pass for the distance to the nearest c on the left, then a right-to-left pass taking the minimum
LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once