← Back to Home

leetcode patterns


2D to 1D mapping

74. Search a 2D Matrix

  • In binary search, we deal with 1D values, l to r. However, in this problem, values are retreived by 2D index (row, col)
  • Since, the matrix elements are sorted, treat it as on single sorted array and perform binary search
  • Thus, we'll convert 1D mid index to find the value in matrix using % and / as appropriate
  • values           1D index           2D index (row,col) mapping
    [ 1, 3, 5, 7]    [ 0, 1,  2,  3]    [  ,  ,      ,  ]
    [10,11,16,20] -> [ 4, 5,  6,  7] -> [  ,  , (1,2),  ]
    [23,30,34,60]    [ 8, 9, 10, 11]    [  ,  ,      ,  ]
    
    - Let's say mid is at pos 6
    - 1D index [6] is converted to 2D index [1,2] to get value 16
    
  • int mid = l + (r - l) / 2;
    int midVal = matrix[mid / cols][mid % cols];
    
  • BacktoBackSWE 🎥

36. Valid Sudoku

  • use HashSets to keep track of numbers in a row, col, and box
  • For box coords, box row = row/3 and box col = col/3

while/switch

Using many while loops one after other instead of using only one

929. Unique Email Addresses

  • use switch to find + and find @ and append substring after it and break (use i = email.len instead of break)