Squares of a Sorted Array - Leetcode 977 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 26 ต.ค. 2024

ความคิดเห็น • 68

  • @chessingh
    @chessingh 2 ปีที่แล้ว +46

    instead of comparing squares of both nums[L] and nums[R], we can compare abs(nums[L]) and abs(nums[R]) because squaring takes more time than absolute. Or we can store and reuse the squared values.

    • @NeetCode
      @NeetCode  2 ปีที่แล้ว +11

      Good point!

    • @orangefield2308
      @orangefield2308 ปีที่แล้ว +14

      @@NeetCode great video! however I think you miscategorized this as a "Binary Search" problem in Leetcode categories, it should prob be an Array or Sliding Window problem

    • @siddharthbalachandran8015
      @siddharthbalachandran8015 ปีที่แล้ว

      @@orangefield2308 You can solve it using binary search actually. Using binary Search, find the minimum positive value possible and then move towards its left and right. Then keep checking which gives a smaller square and add it to the answer array. Then move backwards/leftwards if it was the negative value or forwards/rightwards if it was a positive value.
      It's obviously more complex than the above solution but since it was in the binary search section, I tried solving it like this. Time complexity will be O(logN) + O(N) which is O(N)

  • @momenwadood1342
    @momenwadood1342 2 ปีที่แล้ว +27

    Reversing the array takes time, why not create a prefilled array with dummy values and keep updating from the last element while checking?
    Also store the squared numbers in variables so you only count it once(i don't think it's that important but you can see the difference)
    Great video as always!

    • @saisridhart3133
      @saisridhart3133 2 ปีที่แล้ว

      For that we need length of input array

    • @adventurer2395
      @adventurer2395 2 ปีที่แล้ว +9

      Still O(n)...

    • @StfuSiriusly
      @StfuSiriusly ปีที่แล้ว

      @@adventurer2395 space complexity will be different. prob doesnt matter in an interview but still good to know in case they ask to optimize space

    • @anirbandas12
      @anirbandas12 8 หลายเดือนก่อน

      yep another pointer pos pointing at end does the trick .. also result array will be size of the original ..

    • @thiagot7706
      @thiagot7706 7 หลายเดือนก่อน

      You can also insert at 0
      output.insert(0, nums[p] * nums[p])

  • @laislodi
    @laislodi 2 หลายเดือนก่อน +1

    I used your explanation and wrote a similar code without the need to reverse the array:
    def sortedSquared(array):
    left, right = 0, len(array) - 1
    squares = []
    for num in array:
    far_left = array[left]
    far_right = array[right]
    # alway insert the biggest in the first position
    if abs(far_right) >= abs(far_left):
    squares.insert(0, far_right ** 2)
    right = right - 1
    else:
    squares.insert(0, far_left ** 2)
    left = left + 1
    return squares
    I hope it also helps

  • @sarthakjain1824
    @sarthakjain1824 ปีที่แล้ว +1

    that finding the maximum instead of minimum was genius. It made the code so much cleaner

  • @pavelkovalenko1814
    @pavelkovalenko1814 2 ปีที่แล้ว +6

    Aren't you adding one more O(n) to the complexity while reversing the array in the last step? You could introduce the third pointer (equal to the length of the array) and insert the value at the result array from the end. This way you can ditch the reversing.

  • @pielily
    @pielily ปีที่แล้ว +8

    hey @neetcode, enjoyed this problem and your explanation but why is this tagged as binary search?

  • @abishekbaiju1705
    @abishekbaiju1705 7 หลายเดือนก่อน +2

    My solution was 75 lines long. I don't know i just wrote the solution considering all the edge cases and not thinking of finding the largest number and finding the res array. Thanks for the explanation neetcode.

  • @chasemoney2381
    @chasemoney2381 2 ปีที่แล้ว +11

    Two pointer jutsu
    class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
    l = 0
    r = len(nums) - 1
    index = len(nums) - 1
    res = [1] * len(nums)
    while l abs(nums[r]):
    res[index] = nums[l] **2
    l+=1
    else:
    res[index] = nums[r] **2
    r-=1
    index-=1
    return res

  • @0yustas0
    @0yustas0 2 ปีที่แล้ว +6

    in case of usage: if abs(A[L])>=abs(A[R]):, you can increase your performance on 20 %/ just FYI
    Runtime: 242 ms, faster than 62.87%
    class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
    A = nums
    if not A: return A
    L,R, res = 0,len(A)-1,[]
    while L=abs(A[R]):
    res.append(A[L]**2)
    L+=1
    else:
    res.append(A[R]**2)
    R-=1
    return res[::-1]

  • @sergiofranklin8809
    @sergiofranklin8809 ปีที่แล้ว +4

    Hi, this is in wrong section on neetcode website, it should be two pointers problem not binary search

  • @devbisht6780
    @devbisht6780 8 วันที่ผ่านมา

    idk if its allowed , but leetcode accepted it. beats 100% .
    class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
    return sorted(list(map(lambda x: x * x, nums)))

  • @malakggh
    @malakggh 21 วันที่ผ่านมา +2

    Hey,
    you accedintly put this video under Binary Search category in your website.
    it suppose to be under Two Pointers.

  • @sarvasvarora
    @sarvasvarora 2 ปีที่แล้ว +4

    Interesting I was doing this question yesterday and you released a video today lol

  • @e889.
    @e889. 2 ปีที่แล้ว +3

    Best channel

  • @psibarpsi
    @psibarpsi 2 ปีที่แล้ว

    Wow! Your solution just took away my heart. It is beautiful!

  • @AymenDaoudi-u6h
    @AymenDaoudi-u6h ปีที่แล้ว +2

    I wonder why did you put this problem under Binary Search Category ?

  • @rajarajan1338
    @rajarajan1338 8 หลายเดือนก่อน

    I solved my first question with correct optimal solution without seeing the coding part. Thank you neetcode

  • @shlokkumar8644
    @shlokkumar8644 2 ปีที่แล้ว +2

    U should make a Python DSA course

  • @mariosampetru3073
    @mariosampetru3073 ปีที่แล้ว

    I used a stack in my solution and it is pretty efficient:
    class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
    stack = []
    idx = 0
    for val in nums:
    valSqr = val * val
    while stack and stack[-1] < valSqr:
    nums[idx] = stack.pop()
    idx += 1

    stack.append(valSqr)

    while stack:
    nums[idx] = stack.pop()
    idx += 1

    return nums

  • @nipung8525
    @nipung8525 ปีที่แล้ว

    Improved your solution a bit, give it a check . I used "Insert" rather than "append".
    class Solution(object):
    def sortedSquares(self, nums):
    """
    :type nums: List[int]
    :rtype: List[int]
    """
    res = []
    l,r = 0,len(nums)-1
    while l nums[r]*nums[r]:
    res.insert(0,nums[l]*nums[l])
    l+=1
    else:
    res.insert(0,nums[r]*nums[r])
    r-=1
    return res

    • @sk_4142
      @sk_4142 ปีที่แล้ว

      this is O(n^2), insertion implicitly moves every element in the list to the right every time.

  • @funfingen
    @funfingen ปีที่แล้ว +2

    My question to you is this: if you have a cs degree and you've never thought of code this way, how would you even begin to think that you would build an external list and then reverse it? That would have never ever occurred to me.

    • @pielily
      @pielily ปีที่แล้ว +1

      if you run a few example arrays you'll see the biggest values are at the ends of the array and the solution wants them in ascending order. thats how i came to this solution at least... running examples on any problem can give you lots of intuition that just looking/thinking might not

  • @crane1984
    @crane1984 2 หลายเดือนก่อน

    This was in the binary search section of NC All... I thought I was going crazy haha

  • @s4ltokyo
    @s4ltokyo 2 ปีที่แล้ว

    You can use unshift for javascript instead of reversing it

  • @DoJoStan
    @DoJoStan 2 ปีที่แล้ว +2

    Instead of doing the reverse at the end we can just add the numbers to the beginning of the array instead of appending it.

  • @jimwang8
    @jimwang8 2 ปีที่แล้ว +3

    How about if the array contains all negative or positive numbers?

    • @bhdr111
      @bhdr111 ปีที่แล้ว

      did you find the answer?

  • @krishnajoshi364
    @krishnajoshi364 2 ปีที่แล้ว +2

    Hey thank you so much for the amazing content. I had a question why is the output array built in reverse order rather than from the start/beginning?

    • @tahzibyafi7197
      @tahzibyafi7197 2 ปีที่แล้ว

      because of the way we are utilizing two pointers. We start by looking at the extreme values from both side of the list which happen to be the highest numbers (ignoring the signs), and approach towards the lower numbers (numbers that are closer to 0) as we finish adding the higher numbers to the output list. So we end up with a list where higher numbers are appended first and lower numbers are appended last

  • @Troglodyte2021
    @Troglodyte2021 ปีที่แล้ว

    If you have to sort in the end after all. Why not just return sorted([ n ** 2 for n in nums]) ?

  • @sk_4142
    @sk_4142 ปีที่แล้ว

    No need to reverse array; Java solution:
    class Solution {
    public int[] sortedSquares(int[] nums) {
    int[] res = new int[nums.length];
    int i = nums.length - 1, left = 0, right = i;
    while (left

  • @snowglider400
    @snowglider400 2 ปีที่แล้ว

    @NeetCode Can we do this in place? thanks

  • @Munchen888
    @Munchen888 7 หลายเดือนก่อน

    What about if the nums are [-5,-4, -2,-1]?

  • @knowptr
    @knowptr 2 ปีที่แล้ว +2

    Ur the GOAT

  • @CarolineWaxman-f5e
    @CarolineWaxman-f5e ปีที่แล้ว

    is there a way to do this in-place? without using a new array?

  • @deshpanderamakrishna9862
    @deshpanderamakrishna9862 3 หลายเดือนก่อน

    why is this under Binary search its actually 2 pointers from neetcode sheet

  • @sanooosai
    @sanooosai 11 หลายเดือนก่อน

    thank you sir

  • @AK-kq1mk
    @AK-kq1mk ปีที่แล้ว +1

    Why is this in binary search rather than two pointers?

    • @isdardedilkisifarish3366
      @isdardedilkisifarish3366 ปีที่แล้ว

      You need to search for the first non 0 element which should be done using b search

  • @adityamaurya8034
    @adityamaurya8034 ปีที่แล้ว

    class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
    ans = []
    i, j = 0, len(nums)-1
    while j >= i:
    if abs(nums[i]) > abs(nums[j]):
    ans.append(nums[i]**2)
    i += 1
    else:
    ans.append(nums[j]**2)
    j -= 1
    return ans[::-1]

  • @etchris
    @etchris 2 ปีที่แล้ว +1

    Is a list compreshion not good in this case?
    like sorted([x**2 for x in nums])

    • @etchris
      @etchris 2 ปีที่แล้ว

      oh nvm nlog(n)

  • @AustinWeeks
    @AustinWeeks หลายเดือนก่อน +1

    Hey @NeetCode this problem is in the binary search topic of the NeetCode All on your site. Shouldn't it be in two pointers instead?

  • @thiagot7706
    @thiagot7706 7 หลายเดือนก่อน

    I used memo:
    class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
    p, q = 0, len(nums) - 1
    output = []
    memo = {} # memoization
    while p abs(nums[q]):
    memo[nums[p]] = nums[p] * nums[p]
    output.insert(0, memo[nums[p]])
    p += 1
    else:
    memo[nums[q]] = nums[q] * nums[q]
    output.insert(0, memo[nums[q]])
    q -= 1
    return output

  • @Luc1an_
    @Luc1an_ 2 ปีที่แล้ว

    Sir can you pls do a video on Average of numbers inside Radius K. Thanks😃

  • @jcgan521
    @jcgan521 2 ปีที่แล้ว

    nice explanation , how you are so good

  • @Flatulentadrop
    @Flatulentadrop 3 หลายเดือนก่อน

    Please move that into the two pointer section

  • @adventurer2395
    @adventurer2395 2 ปีที่แล้ว

    Instead of looping through the left and right pointers and then looping again to reverse, you can just loop through the result array in decreasing order, updating the right and left pointers. Example:
    class Solution:
    def sortedSquares(self, nums):
    length = len(nums)
    result = [0] * length
    left, right = 0, length - 1
    for i in range(length - 1, -1, -1):
    if abs(nums[left]) > abs(nums[right]):
    result[i] = nums[left] * nums[left]
    left += 1
    else:
    result[i] = nums[right] * nums[right]
    right -= 1
    return result

  • @Cruzylife
    @Cruzylife ปีที่แล้ว

    wow that was tricky

  • @winterheat
    @winterheat ปีที่แล้ว

    don't know if this is a good question to test a candidate. I can see an IQ 300 candidate, superb programmer, if he didn't see this question before, he may not reach this optimal answer, versus a person who sucked at programmer but have seen this problem before, will start with this, "oh two pointers from both sides" method and get hired? That's totally unjust

  • @FinazzoCodes
    @FinazzoCodes 2 ปีที่แล้ว

    can someone explain line 5 of his code

    • @hamoodhabibi7026
      @hamoodhabibi7026 2 ปีที่แล้ว +1

      he basically initialized his left and right pointer to index 0 and last index. SO that we can check both ends of the array at the same time

  • @CPS_XI
    @CPS_XI 7 หลายเดือนก่อน

    💯❤

  • @lucidity1230
    @lucidity1230 หลายเดือนก่อน

    I'm so dumb

  • @NotNotNithin
    @NotNotNithin 2 ปีที่แล้ว

    Java solution
    public static int[] makeSquares(int[] arr) {
    int n = arr.length;
    int[] squares = new int[n];
    int highestSquareIdx = n - 1;
    int left = 0, right = n - 1;
    while (left rightSquare) {
    squares[highestSquareIdx--] = leftSquare;
    left++;
    } else {
    squares[highestSquareIdx--] = rightSquare;
    right--;
    }
    }
    return squares;
    }

    • @Ace-ex9gg
      @Ace-ex9gg ปีที่แล้ว

      this still use O(n) extra space