Python Program to Find median in row wise sorted matrix
Last Updated :
31 Jul, 2023
We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.
Examples:
Input : 1 3 5
2 6 9
3 6 9
Output : Median is 5
If we put all the values in a sorted
array A[] = 1 2 3 3 5 6 6 9 9)Input: 1 3 4
2 5 6
7 8 9
Output: Median is 5
Python Program to Find median in row wise sorted matrix
The simplest method to solve this problem is to store all the elements of the given matrix in an array of size r*c. Then we can either sort the array and find the median element in O(r*clog(r*c)) or we can use the approach discussed here to find the median in O(r*c). Auxiliary space required will be O(r*c) in both cases.
An efficient approach for this problem is to use a binary search algorithm. The idea is that for a number to be median there should be exactly (n/2) numbers which are less than this number. So, we try to find the count of numbers less than all the numbers. Below is the step by step algorithm for this approach:
Algorithm:
- First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row.
- Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than our mid. And accordingly change the min or max.
- For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number.
Below is the implementation of the above approach:
Python3
# Python program to find median of matrix
# sorted row wise
from bisect import bisect_right as upper_bound
MAX = 100;
# Function to find median in the matrix
def binaryMedian(m, r, d):
mi = m[0][0]
mx = 0
for i in range(r):
if m[i][0] < mi:
mi = m[i][0]
if m[i][d-1] > mx :
mx = m[i][d-1]
desired = (r * d + 1) // 2
while (mi < mx):
mid = mi + (mx - mi) // 2
place = [0];
# Find count of elements smaller than mid
for i in range(r):
j = upper_bound(m[i], mid)
place[0] = place[0] + j
if place[0] < desired:
mi = mid + 1
else:
mx = mid
print ("Median is", mi)
return
# Driver code
r, d = 3, 3
m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]]
binaryMedian(m, r, d)
# This code is contributed by Sachin BIsht
Output:
Median is 5
Time Complexity: O(32 * r * log(c)). The upper bound function will take log(c) time and is performed for each row. And since the numbers will be max of 32 bit, so binary search of numbers from min to max will be performed in at most 32 ( log2(2^32) = 32 ) operations.
Auxiliary Space : O(1)
Python Program to Find median in row wise sorted matrix Using list comprehension and sorted() function
In this method, we first flatten the matrix into a single list using list comprehension and the sorted() function.
Then we find the median element(s) based on the length of the flattened list and return the result. We don't need to import any external modules or use binary search since the list is already sorted. The code looks considerably simpler using this approach.
Below is the implementation of the above approach.
Python3
# Python program to find median of matrix
# sorted row wise
# Function to find median in the matrix
def binaryMedian(m, r, d):
# Flatten the matrix into a list and sort it
sorted_list = sorted([m[i][j] for i in range(r) for j in range(d)])
# Find the median element(s)
mid = (r * d - 1) // 2
if (r * d) % 2 == 0:
return (sorted_list[mid] + sorted_list[mid+1]) / 2
else:
return sorted_list[mid]
# Driver code
r, d = 3, 3
m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]]
print("Median is", binaryMedian(m, r, d))
Time Complexity: O(r * d * log(rd)), r and d are given in the input
Auxiliary Space: O(rd), because we create a new list of length r*d to store the flattened matrix.
Please refer complete article on Find median in row wise sorted matrix for more details!
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read