Leetcode Problem 977. Squares of a Sorted Array

977. Squares of a Sorted Array

Leetcode Solutions

Two Pointer Approach

  1. Initialize two pointers: left at the start of the array and right at the end of the array.
  2. Create an array result of the same length as nums to store the squares in non-decreasing order.
  3. Use a loop to iterate from the end of the result array to the beginning. a. Compare the absolute values of nums[left] and nums[right]. b. If abs(nums[left]) is greater than abs(nums[right]), square nums[left] and place it in the current position of result, then increment left. c. Otherwise, square nums[right] and place it in the current position of result, then decrement right.
  4. Continue this process until all positions in result are filled.
  5. Return the result array.
UML Thumbnail

Simple Squaring and Sorting Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...