LeetCode Search A 2D Matrix Solution Explained - Java

Sdílet
Vložit
  • čas přidán 13. 04. 2019
  • The Best Place To Learn Anything Coding Related - bit.ly/3MFZLIZ
    Join my free exclusive community built to empower programmers! - www.skool.com/software-develo...
    Preparing For Your Coding Interviews? Use These Resources
    --------------------
    (My Course) Data Structures & Algorithms for Coding Interviews - thedailybyte.dev/courses/nick
    AlgoCademy - algocademy.com/?referral=nick...
    Daily Coding Interview Questions - bit.ly/3xw1Sqz
    10% Off Of The Best Web Hosting! - hostinger.com/nickwhite
    Follow My Twitter - / nicholaswwhite
    Follow My Instagram - / nickwwhite
    Other Social Media
    ----------------------------------------------
    Discord - / discord
    Twitch - / nickwhitettv
    TikTok - / nickwhitetiktok
    LinkedIn - / nicholas-w-white
    Show Support
    ------------------------------------------------------------------------------
    Patreon - / nick_white
    PayPal - paypal.me/nickwwhite?locale.x...
    Become A Member - / @nickwhite
    #coding #programming #softwareengineering
  • Věda a technologie

Komentáře • 58

  • @avi007i
    @avi007i Před 2 lety +19

    The way I understood midpoint_element = matrix[midpoint/columns][midpoint%columns] is -
    To convert 2D array into 1d array, you *multiply* rows by columns on line 9, int right = rows * columns - 1
    So to convert it back to 2D, we do the opposite of the above multiplication and hence we *divide* the index value by columns to get row value. And whatever remaining which is midpoint%columns will be the column value.

  • @vaibhavgupta6428
    @vaibhavgupta6428 Před 4 lety +5

    I was truly missing the catch to compute mid-Point! Thanks Bro! Great work.

  • @alpishjain1317
    @alpishjain1317 Před 3 lety +3

    great explanation!I always look forward to this channel whenever i'm stuck.

  • @MrKracx
    @MrKracx Před 3 lety +15

    In case anyone is confused about the midpoint_element = matrix[midpoint/columns][midpoint%columns], here is my way of understanding:
    In the example at @11:28 , we have 3 rows, 4 columns
    When finding the initial midpoint, we do (0+11)/2 = 5
    Think about this statement very carefully:
    Every row has 4 columns. Read it again. Every row has 4 columns. Read it once more. 1 row consists of 4 columns.
    So if I'm given an index, and I need to calculate the row, its just dividing by the number of columns.
    First row has columns 0,1,2,3
    Second row has columns 4,5,6,7
    For calculating the column number, you have to realize that the column of index = 0 is same as the column of index = 4. Similarly, the column of index 1 = column of index 5.
    That is, index 0 and 4 are still considered column 0. Index 1 and 5 are still considered column 1.
    In this sense its just wrapping around, and when we have something like this, we use mod. So index % cols will give you the column.
    If you are given a 2d index and want to convert back to 1d, it is just the reverse.
    Say we are given the index [1][1]. We saw above that this is actually index 5 on a 1d list.
    The [1] (row) says that we are on the first row. What this means is that we crossed 4 columns (passed the 0th row), and are now on the first row. So, we know that our answer will consist of row_index * num_cols
    After that, the [1] (col) just means that we have moved this much ahead from the start of the row. So the formula becomes (row_index * num_cols) + col_index
    If it was [1][0], this means that we are on the first row, and have not moved up any column. Similarly, [1][3] means first row, and moved to 4th col.

  • @pandupvpk
    @pandupvpk Před 4 lety +7

    lol..loved the last midpoint explanation!!

  • @dadingchen8323
    @dadingchen8323 Před 2 lety +5

    midpoint/columns give row numbers because it is basically computing how many full columns can you get. For example, in the video, 4 columns make one row. So midpoint/column basically is calculating how many groups of 4 columns you can get which in turn is row number since each row has 4 columns. And it is obvious that mid*columns would give you column number because after computing the row number after division all it left is just the not completed columns for the matrix which is the column number.

    • @dadingchen8323
      @dadingchen8323 Před 2 lety

      Sorry it should be midpoint%columns for columns numbers

    • @shankarsaravanan9206
      @shankarsaravanan9206 Před 2 lety

      Thanks for the explanation man!!! I actually couldn't understand when nick explained. I could understand this better now with your explanation.

  • @yitingg7942
    @yitingg7942 Před 3 lety +4

    Thank you for taking the time to really trying to explain it Nick, appreciate it!

  • @tasneemayham974
    @tasneemayham974 Před rokem

    THIS IS THE BEST VIDEO!!!! I was soo engrossed especially when you were explaining!!

  • @NaserMohdBaig
    @NaserMohdBaig Před 4 lety +1

    Absolute genius! Thanks for this amazing explanation. I don't know Java but understood everything you said, thanks to your narration.

  • @aayushpagare9366
    @aayushpagare9366 Před 3 lety +1

    Dude you are a genius 😳🙏🏻

  • @hamoodhabibi7026
    @hamoodhabibi7026 Před rokem +2

    Okay, how i understood it in words
    matrix_mid = matrix[mid // col][mid % col] is
    mid // col == the number of rows we have completed
    mid % col == the number of extra cells we have left (which is our cols)

  • @achmadabdillah9567
    @achmadabdillah9567 Před 10 měsíci

    amazing man, thank you so much

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

    No need to buy premium; we nick for solutions.....

  • @triplestrikee875
    @triplestrikee875 Před 2 lety

    Great explanation! Liked the solution. The part converted the regular midpoint to the matrix position is very smart, make the problem very close to the "regular" binary search. Thanks a lot.

  • @anirbanchakraborty690
    @anirbanchakraborty690 Před 4 lety +2

    Hey nick, can you tell me the intuition behind when to choose while(left

  • @samuelvalentine7846
    @samuelvalentine7846 Před 11 měsíci

    This is my own solution that i came up with in 30 mins.. I haven't tried it on leetcode this
    def find_in2(lst: list, number: int):
    left = 0
    right = len(lst) - 1
    while left lst[mid][0] and number < lst[mid][-1]:
    return number in lst[mid]
    if number > lst[mid][-1]:
    left = mid + 1
    else:
    right = mid - 1
    return False
    It compares the left most and right most integer since each row is sorted

  • @mohamedhesham6008
    @mohamedhesham6008 Před 2 lety

    very clever thank you

  • @vishalsinghpanwar2972

    how to get this intuition of using [mid%columns] and [mid/columns]............could have never thought of this.........any idea how to get this idea/intuition when we come across such questions?

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

    Could someone quickly explain why we set:
    right = midpoint +1
    left = midpoint -1
    Specifically why we +1 and -1?
    Thanks

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

      After some more debugging i can answer my own question (posting on here in case it's useful for anyone else) - we've already verified the midpoint is not the target element, so we're excluding it from the right/left bounds on the next iteration of the loop.

  • @tonytony6858
    @tonytony6858 Před rokem

    This is why: mid_point = left + (right - left)/2 = (right - left)/2
    left + (right - left)/2
    = (2left + right - left)/2
    = (right - left)/2

  • @ayushgoyal6079
    @ayushgoyal6079 Před 4 lety +1

    it doesnt pass many test cases
    can you explain why it is so?

  • @glenfernandes253
    @glenfernandes253 Před 3 lety

    while doing Binary search I am confused as to when to use:
    1) left

    • @aba0101
      @aba0101 Před 2 lety

      Hi, the comparison is not between left and right, it is comparing the mid to the target, if the mid number is larger than the target, it means the target exists in the section between 0 to mid because the array is sorted. Hopefully my explanation will be helpful. : )

  • @chodingninjas7415
    @chodingninjas7415 Před 4 lety

    great.

  • @munishmisra169
    @munishmisra169 Před rokem

    It should be :
    int cols = matrix[0].length;
    int rows = matrix.length;
    All test cases will be passed.

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

    This dude is hot af. Just love his explanation so much damn.

  • @parwana1000
    @parwana1000 Před 3 lety

    Why thumbs down ?
    Great work

  • @jacobl.743
    @jacobl.743 Před 4 lety +4

    "Your brain will work better if you eat healthy"
    Nick: 0:13

  • @MrMadan1989
    @MrMadan1989 Před 4 lety +1

    Does the solution of 2x2 matrix? for example [[1,4],[2,5]] and element to find is 2

    • @thndesmondsaid
      @thndesmondsaid Před 4 lety +1

      Hey Madan I was stuck on this too, looks like both of us were working on Search a 2D Matrix II not Search a 2D matrix which requires a slightly different approach with O(m+n) time complexity

    • @sivasubramaniansivaramakri8472
      @sivasubramaniansivaramakri8472 Před 3 lety

      This solution is for Q.74 and will not work for Q.240. 240 has a slight difference.

  • @techmoon_
    @techmoon_ Před 2 lety

    Thanks Thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks thanks

  • @Priyam6F4
    @Priyam6F4 Před rokem

    Intuition
    This problem will purely be solved on the core principles of how a 2D matrix works,its traversal and a few comparisons.
    Approach
    We assign i=0 and j=n-1, means i is at start of the row and j is present at the start of the last column. We start comparing from j=n-1. Basically,the comparison is starting from the last element of the first row. Now,if observed closely, the last element of the first row, moving downwards from there will always result in a greater value as the 2D Matrix happens to be sorted. If target is smaller, there is no point moving down. Hence, we decrement j and move to the previous column. We check again, if target is still smaller (matrix[i][j]>target) we decrement j again.
    observe one thing. As we move from the extreme right to left, we notice that values are eventually decreasing for the ith row. So we are bound to reach a point, where matrix[i][j] has a smaller value than target. If so, we now increment i and move to the row below,which gets us closer to the target.
    Finally we reach a point where we find the target.
    Complexity
    Time complexity:
    O(m+n)
    Space complexity:
    O(1)
    Code
    class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
    int m = matrix.length; // row
    int n = matrix[0].length; // col
    int i = 0;
    int j = n - 1;
    while (i >= 0 && i < m && j >= 0 && j < n) {
    if (matrix[i][j] == target) {
    return true;
    } else if (matrix[i][j] > target) {
    j--;
    } else if (matrix[i][j] < target) {
    i++;
    }
    }
    return false;
    }
    }

  • @komalbhalge5119
    @komalbhalge5119 Před 4 lety

    [[1,4],[2,5]]
    2
    Code couldn’t pass the above test case.

    • @starc701
      @starc701 Před 4 lety +1

      just check, while(left

    • @manish7897
      @manish7897 Před 3 lety +2

      Wrong input

    • @aayushpagare9366
      @aayushpagare9366 Před 3 lety

      No

    • @AdithyareddyCh
      @AdithyareddyCh Před 3 lety +1

      For anyone who is getting the same error, this logic works for search a 2d matrix question, but not for search for 2d matrix 2.

    • @wolfofthelight5690
      @wolfofthelight5690 Před 3 lety +2

      Binary search only works on a sorted list. Your input list is not sorted.

  • @studentcorner7641
    @studentcorner7641 Před 4 lety

    class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
    int row=matrix.length; if(row==0) return false;
    int col=matrix[0].length;
    for(int i=0;i