imashutosh51

Median in a row-wise sorted matrix

Feb 9th, 2026 (edited)
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.07 KB | None | 0 0
  1. """
  2. Since n and m are odd, the total number of elements (N = n * m) is always odd.
  3. suppose we flattened the matrix and sorted them into a 1-d array.In a sorted list of N elements, the median is the middle value at index (n * m) // 2.
  4.  
  5. The Key Rule:
  6. The median of a sorted 1-d array is the first from left side or (smallest) element where the count of elements
  7. less than or equal that element(means median) is GREATER than the median index ie. (N // 2) means so it can be greater than equal to (N//2)+1
  8.  
  9. Key rule more refined: The smallest number x such that at least (n*m)//2 + 1 elements are ≤ x.
  10.  
  11. bisect_left: It returns the first index where an element can be inserted without breaking the sorted order.
  12. bisect_right: It returns the last index where an element can be inserted without breaking the sorted order.
  13.  
  14. Examples (Total elements N = 9, Median Index = 4):
  15. --------------------------------------------------
  16. 1. Standard Case (No duplicates):
  17.   Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  18.   - Median is 5.
  19.   - count of elements <= 5 is 5. (5 > 4(median index), so this works!)
  20.   - count of elements <= 4 is only 4. (4 is not > 4, so 4 can't be median).
  21.  
  22. 2. Duplicates on the Left (Median is 5):
  23.   Array: [1, 2, 5, 5, 5, 6, 7, 8, 9]
  24.   - Index 4 is the middle '5'.
  25.   - How many elements are <= 5? There are 5 elements.
  26.   - Since 5 > 4, 5 is a candidate for median.
  27.  
  28. 3. Duplicates on Both Sides (Median is 5):
  29.   Array: [1, 5, 5, 5, 5, 5, 5, 5, 9]
  30.   - Index 4 is '5'.
  31.   - How many elements are <= 5? There are 8 elements.
  32.   - Since 8 > 4, 5 is a candidate. We look for the first number
  33.     to satisfy this, which is 5.
  34.   - the number less than 5 and which can be a probable mean have count of numbers <=1 is only 1 which is less than N//2 so it is not possible.
  35.  
  36. so we will check the numbers between min element and max element of the matrix whose count <= N//2 and that element should be smallest or first from
  37. the left, if it satisfies, we will return it.
  38.  
  39. Time: O(log(Max-Min) * N * log(M))
  40. Space: O(1)
  41.  
  42. Trick: Rows can internally sorted but row might not be gloaball sorted eg [[5,6,7],[2,3,4]] so you can't consider the 5 as the left range.
  43. """
  44.  
  45. from bisect import bisect_right
  46. class Solution:
  47.     def median(self, mat):
  48.         n=len(mat) #row
  49.         m=len(mat[0]) #col
  50.         low = min(row[0] for row in mat)
  51.         high = max(row[-1] for row in mat)
  52.  
  53.         req = (n * m) // 2 #this many elements should be smaller than or equal to the median in the array
  54.  
  55.         while low <= high:
  56.             mid = (low + high) // 2
  57.  
  58.             cnt = 0
  59.             for row in mat: #traversing on all the rows
  60.                 cnt += bisect_right(row, mid)   # count of elements <= mid in all the rows of the matrix
  61.  
  62.             if cnt <= req: #means the median in right
  63.                 low = mid + 1
  64.             else:
  65.                 high = mid - 1 #even the condition satisfies, we will keep searching elements in the left, may be some smaller element than current element satisfies the condition.the search will stop when low>right
  66.  
  67.         return low
  68.        
Advertisement
Add Comment
Please, Sign In to add comment