Leetcode - Kth Smallest Element in a Sorted Matrix (Python)

Sdílet
Vložit
  • čas přidán 6. 07. 2021
  • July 2021 Leetcode Challenge
    Leetcode - Kth Smallest Element in a Sorted Matrix #378
    Difficulty: Medium
  • Věda a technologie

Komentáře • 8

  • @GodisgudAQW
    @GodisgudAQW Před 2 lety +1

    For counting the number of elements less than or equal, you can do it in O(n) instead of O(n log n). You can basically go through each column of numbers (from left to right), starting at a column size of n, and add up the largest column size that allows every number in the column to be less than or equal to the target.
    Since you know that the last element in the column is the largest, if that element is less than or equal to the target, then you can immediately add the entire column size to your count and proceed to the next column.
    On the other hand, if the last element in the column is too big, you reduce your column size by 1. The key insight here is that once an element is too big, all elements to the right of it (in the same row) will also be too big. But once you reduce your column size, that element might still be within bounds, so you just keep running these steps until you reach the end.

  • @naramukuriht
    @naramukuriht Před 3 lety

    this is gold. I was at first taken aback when the brute force algorithm was accepted. In fact I did similar brute force as what you mentioned here, excepting I used list comprehension for flattening the matrix.

  • @nuoalei1626
    @nuoalei1626 Před 2 lety +2

    There could be cases that the return value is not in the matrix. I think instead of just return count in the first binary search, we need to return the value larger and the value smaller than the mid that is in the matrix. If there is something like 12.1 in the matrix. We may not get the value. But the method are very good and informational.

  • @samw2066
    @samw2066 Před 2 lety +2

    where is bisect_right defined ? does not appear to be and I get an error running the code as a result. Am i missing something ?

    • @timc3406
      @timc3406  Před 2 lety

      It's auto imported for leetcode, you can import it from python3 docs.python.org/3/library/bisect.html

  • @taniyachauhan7382
    @taniyachauhan7382 Před 6 měsíci

    What are you doing in the bisect_right part? What is the logic behind that?

  • @kartikeyaverma
    @kartikeyaverma Před 3 lety

    Can we just not flatten this 2D list, then sort it and return the kth element? Is something wrong with it?

    • @reactionchamber
      @reactionchamber Před 2 lety +1

      it works, but is clearly not the optimal solution as it takes O(n^2) time and space