LeetCode Entry

977. Squares of a Sorted Array

02.03.2024 easy 2024 kotlin rust

Sorted squares.

977. Squares of a Sorted Array easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/526

Problem TLDR

Sorted squares.

Intuition

We can build the result bottom up or top down. Either way, we need two pointers: for the negative and for the positive.

Approach

Can we made it shorter?

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


  fun sortedSquares(nums: IntArray): IntArray {
    var i = 0; var j = nums.lastIndex;
    return IntArray(nums.size) {
      (if (abs(nums[i]) > abs(nums[j]))
        nums[i++] else nums[j--]).let { it * it }
    }.apply { reverse() }
  }


  pub fn sorted_squares(nums: Vec<i32>) -> Vec<i32> {
    let (mut i, mut j) = (0, nums.len() - 1);
    let mut v: Vec<_> = (0..=j).map(|_|
      if nums[i].abs() > nums[j].abs() {
        i += 1; nums[i - 1] * nums[i - 1]
      } else { j -= 1; nums[j + 1] * nums[j + 1] })
      .collect(); v.reverse(); v
  }