For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
1. Introduction
6. PyTorch
9. AI Tutorial
10. Airflow Tutorial
11. Android Studio
12. Android Tutorial
13. Animation CSS
16. Apex Tutorial
17. App Tutorial
18. Appium Tutorial
21. Armstrong Number
22. ASP Full Form
23. AutoCAD Tutorial
27. Belady's Anomaly
30. Bipartite Graph
35. Button CSS
39. Cobol Tutorial
46. CSS Border
47. CSS Colors
48. CSS Flexbox
49. CSS Float
51. CSS Full Form
52. CSS Gradient
53. CSS Margin
54. CSS nth Child
55. CSS Syntax
56. CSS Tables
57. CSS Tricks
58. CSS Variables
61. Dart Tutorial
63. DCL
65. DES Algorithm
83. Dot Net Tutorial
86. ES6 Tutorial
91. Flutter Basics
92. Flutter Tutorial
95. Golang Tutorial
96. Graphql Tutorial
100. Hive Tutorial
103. Install Bootstrap
107. Install SASS
109. IPv 4 address
110. JCL Programming
111. JQ Tutorial
112. JSON Tutorial
113. JSP Tutorial
114. Junit Tutorial
115. Kadanes Algorithm
116. Kafka Tutorial
117. Knapsack Problem
118. Kth Smallest Element
119. Laravel Tutorial
122. Linear Gradient CSS
129. Memory Hierarchy
133. Mockito tutorial
134. Modem vs Router
135. Mulesoft Tutorial
136. Network Devices
138. Next JS Tutorial
139. Nginx Tutorial
141. Octal to Decimal
142. OLAP Operations
143. Opacity CSS
144. OSI Model
145. CSS Overflow
146. Padding in CSS
148. Perl scripting
149. Phases of Compiler
150. Placeholder CSS
153. Powershell Tutorial
158. Pyspark Tutorial
161. Quality of Service
162. R Language Tutorial
164. RabbitMQ Tutorial
165. Redis Tutorial
166. Redux in React
167. Regex Tutorial
170. Routing Protocols
171. Ruby On Rails
172. Ruby tutorial
173. Scala Tutorial
175. Shadow CSS
178. Snowflake Tutorial
179. Socket Programming
180. Solidity Tutorial
181. SonarQube in Java
182. Spark Tutorial
189. TCP 3 Way Handshake
190. TensorFlow Tutorial
191. Threaded Binary Tree
196. Types of Queue
197. TypeScript Tutorial
198. UDP Protocol
202. Verilog Tutorial
204. Void Pointer
205. Vue JS Tutorial
206. Weak Entity Set
207. What is Bandwidth?
208. What is Big Data
209. Checksum
211. What is Ethernet
214. What is ROM?
216. WPF Tutorial
217. Wireshark Tutorial
218. XML Tutorial
In computer science and mathematics, knowing how to find the median of two sorted arrays is a key skill for analyzing data efficiently. The median represents the middle value when two sorted arrays are combined, giving insight into the dataset’s central tendency.
This tutorial will guide you through multiple efficient methods to find the median of two sorted arrays, whether the arrays are of equal or different sizes. With clear examples, outputs, and explanations, you’ll learn to implement these techniques confidently in Python, C, or other programming languages, making it perfect for beginners and enthusiasts alike.
Learning Data Structures can seem overwhelming at first, but with practice and the right resources, it becomes a valuable skill for any Engineer. upGrad's Software Engineering Courses provide hands-on experience in mastering Data Structures and building scalable, high-performance software solutions.
The median of two sorted arrays is a pivotal value, often used in statistics, data analysis, and algorithm optimization. Efficiently computing this value is crucial for improving performance in various applications. In this article, we will explore different techniques to calculate the median, including merging arrays, binary search, priority queues, and simulated stacks. By the end of this tutorial, you’ll be highly skilled and able to use this versatile and useful tool in a variety of applications. So, let’s get started!
Concept:
To find the median of two sorted arrays with different sizes, we can merge the arrays virtually using a two-pointer approach without merging them physically. We maintain two pointers, one for each array, and move them accordingly to keep track of the middle elements.
Take your programming skills to the next level and gain expertise for a thriving tech career. Discover top upGrad programs to master data structures, algorithms, and advanced software development.
Example:
Output:
Explanation:
- In this example, the code defines a function named `find_median`, which takes two sorted arrays `arr1` and `arr2` as input parameters.
- The function merges the two arrays into a new list called ‘merged', maintaining the sorted order of elements.
- It uses two pointers `i` and `j` to traverse through both arrays `arr1` and `arr2`.
- The merged array contains all elements from `arr1` and `arr2` in sorted order.
- The median is then calculated based on the merged array's length, `n`.
- If the total number of elements in the merged array is even, the median is the average of the two middle elements.
- If the total number of elements is odd, the median is the middle element itself.
- The `find_median` function returns the calculated median, which is printed in the example using the given arrays `[2, 4, 6, 8, 10]` and `[1, 3, 5]`.
- The output will be: `Median: 4`.
Also Read: 50+ Data Structures and Algorithms Interview Questions for 2025
Concept:
To determine the median using binary search, the arrays must be partitioned such that the elements on the left are smaller than the elements on the right. The median is then the average of the largest element on the left and the smallest element on the right.
Example:
Output:
Explanation:
Also Read: Difference Between Stack and Array
Concept:
We can use a priority queue data structure to merge the two arrays efficiently while maintaining the correct order of elements.
Example:
Output:
Explanation:
In this example, the two sorted arrays are [1, 3, 5, 7] and [2, 4, 6]. We use a priority queue to merge the arrays, and the merged queue becomes [1, 2, 3, 4, 5, 6, 7]. The median is 4.0.
Concept:
The simulated stack performs operations similar to a merge operation in merge sort, helping us find the median effectively.
Example:
def findMedianSortedArrays(arr1, arr2):
m, n = len(arr1), len(arr2)
total = m + n
stack = []
ptr1, ptr2 = 0, 0
while len(stack) < total // 2 + 1:
if ptr1 < m and (ptr2 >= n or arr1[ptr1] < arr2[ptr2]):
stack.append(arr1[ptr1])
ptr1 += 1
else:
stack.append(arr2[ptr2])
ptr2 += 1
if total % 2 == 0:
return (stack[-1] + stack[-2]) / 2.0
else:
return float(stack[-1])
# Example
arr1 = [1, 3, 8, 9, 15]
arr2 = [7, 11, 18, 19, 21, 25]
median = findMedianSortedArrays(arr1, arr2)
print(f"Median: {median}")
Output:
Median: 9.0
The median of these two sorted arrays is 9.0. This is the average of the two middle elements from the merged array: [1, 3, 7, 8, 9, 11, 15, 18, 19, 21], which are 8 and 9.
Explanation:
Also Read: How to Implement Stacks in Data Structure? Stack Operations Explained
Concept:
When both input arrays have the same size, finding the median is relatively straightforward. We can merge the arrays and calculate the median based on the merged result.
Example (using pseudo-code):
Suppose we have two sorted arrays, `arr1` and `arr2`, each of size `n`. We will virtually merge the arrays to find the median.
Example (using values):
Suppose we have two sorted arrays [1, 3, 5] and [2, 4, 6], both with the same size of 3.
In the above example, the function findMedian efficiently finds the median of the merged array [1, 2, 3, 4, 5, 6], which is 3.5.
Please note that this is a pseudo-code representation of the concept, and you can use similar merging and median calculation steps in any programming language of your choice to find the median of two sorted arrays of the same size.
Concept:
We can implement various algorithms to find the median of two sorted arrays in C. One common approach is to use a two-pointer technique to virtually merge the arrays.
Example in C:
Output:
Explanation:
Also Read: Array in C Explained: Boost Your Coding Skills with Proven Examples
Concept:
Divide and conquer is a widely used technique to find the median of two sorted arrays efficiently. We partition both arrays and compare the elements around the median to arrive at the answer.
Example:
Output:
Explanation:
Also Read: Understanding One Dimensional Array in C: Key Concepts and Usage
Concept:
The divide and conquer algorithm divides two sorted arrays into halves, with smaller elements in the left half. Finding the partition points determines the median of the combined arrays. This approach lowers the search space in logarithmic time (O(log(min(m, n))) and processes even and odd-sized arrays.
Example:
```java
public class MedianOfTwoSortedArrays {
public static double findMedian(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
if (m > n) {
// Swap the arrays and sizes to ensure nums1 is smaller.
int[] tempArr = nums1;
nums1 = nums2;
nums2 = tempArr;
int tempSize = m;
m = n;
n = tempSize;
}
int imin = 0, imax = m, halfLen = (m + n + 1) / 2;
while (imin <= imax) {
int i = (imin + imax) / 2;
int j = halfLen - i;
if (i < m && nums2[j - 1] > nums1[i]) {
// i is too small, increase it
imin = i + 1;
} else if (i > 0 && nums1[i - 1] > nums2[j]) {
// i is too big, decrease it
imax = i - 1;
} else {
// i is perfect, get the median
int maxLeft;
if (i == 0) {
maxLeft = nums2[j - 1];
} else if (j == 0) {
maxLeft = nums1[i - 1];
} else {
maxLeft = Math.max(nums1[i - 1], nums2[j - 1]);
}
if ((m + n) % 2 == 1) {
return maxLeft;
}
int minRight;
if (i == m) {
minRight = nums2[j];
} else if (j == n) {
minRight = nums1[i];
} else {
minRight = Math.min(nums1[i], nums2[j]);
}
return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8, 10};
double median = findMedian(arr1, arr2);
System.out.println("Median: " + median);
}
}
```
Output:
Explanation:
In this example, we have two sorted arrays, `arr1 = {1, 3, 5, 7}` and `arr2 = {2, 4, 6, 8, 10}`.
The `findMedian` function uses the divide and conquer approach to find the median. After evaluating the arrays, the median is calculated as 5.5.
The time complexity of this algorithm is O(log(min(m, n))), where m and n are the sizes of the two input arrays. The example demonstrates how the divide and conquer technique efficiently finds the median in logarithmic time complexity, even for larger arrays.
The median of two sorted arrays is a crucial concept with numerous practical applications in computer science and data analysis. By mastering the efficient techniques discussed, merging arrays, binary search, priority queues, and simulated stacks, you can confidently find the median of two sorted arrays for arrays of any size. Applying these methods optimizes your algorithms and equips you to handle real-world problems effectively, making your data processing faster and more accurate.
If one array is empty, the median is determined entirely by the non-empty array. For an odd-length array, the median is the middle element, while for an even-length array, it is the average of the two middle elements. Handling empty arrays is essential to accurately find the median of two sorted arrays and avoid errors in computation.
Yes, sorting is required if the arrays are not already sorted. To find the median of two sorted arrays, you must identify whether the total number of elements is odd or even. For an odd total, the median is the center element; for an even total, it is the average of the two middle elements. Correctly managing the sort ensures accurate results.
While finding the median, algorithms perform best when arrays are pre-sorted. Quicksort is generally the most efficient sorting algorithm for unsorted arrays, especially with unknown input properties. Efficient sorting is critical when attempting to find the median of two sorted arrays efficiently.
To find the median of two sorted arrays of unequal lengths, you can either merge both arrays and then compute the median or use a binary search-based partition approach. Binary search ensures O(log(min(n, m))) efficiency, whereas merging is simpler but takes O(n + m) time. The choice depends on array sizes and performance requirements.
Yes, binary search is highly effective for finding the median of two sorted arrays without fully merging them. The method involves partitioning the smaller array and ensuring all elements on the left are smaller than those on the right. This provides an optimized O(log(min(n, m))) solution.
Using the merge method, the time complexity is O(n + m), where n and m are the lengths of the arrays. While simple to implement, this approach is less optimal for very large arrays compared to binary search, but it is easy to understand and verify when learning to find the median of two sorted arrays.
Yes, you can find the median of two sorted arrays using binary search-based partitioning. This approach avoids full merging and instead calculates the median by comparing elements at partition boundaries, making it highly efficient in terms of both time and space.
Duplicate elements do not affect the median calculation. Algorithms for finding the median of two sorted arrays consider positions in the sorted order rather than unique values, so repeated numbers are automatically incorporated into the calculation.
Yes, a priority queue or min-max heap can be used to dynamically find the median of two sorted arrays. By maintaining a balanced heap structure, you can insert elements from both arrays and efficiently retrieve the median, which is useful in streaming or real-time applications.
Both arrays should contain comparable numeric types to find the median of two sorted arrays. Mixing types like integers and floats is generally acceptable, but non-numeric types require conversion. Proper type handling ensures accurate median calculations.
Yes, sorting is essential for efficient median computation. Binary search or partition-based methods require pre-sorted arrays to correctly find the median of two sorted arrays. Without sorting, the results may be incorrect or algorithms may require additional sorting steps.
For an odd total number of elements, the median is the single middle element. For an even total, it is the average of the two middle elements. This distinction is crucial when you find the median of two sorted arrays, as different formulas are used depending on the total number of elements.
Yes, recursion can partition arrays to find the median of two sorted arrays. By reducing the problem size at each step, recursive methods efficiently implement divide-and-conquer strategies such as binary search, making them suitable for large arrays.
By using binary search partitioning instead of merging, you can find the median of two sorted arrays in O(1) extra space. This approach avoids creating a new array and maintains memory efficiency while achieving logarithmic time complexity.
If both arrays are empty, there is no median to compute. Algorithms should handle this edge case properly, either by returning an error or a predefined value. Proper validation ensures safe computation when attempting to find the median of two sorted arrays.
In Python, you can merge arrays and compute the median or use bisect for binary search to efficiently find the median of two sorted arrays. List slicing and indexing make it easy to access central elements once arrays are partitioned or merged.
Yes, in C or Java, you can merge arrays manually or use binary search for partitioning. Efficiently implemented loops and condition checks allow you to find the median of two sorted arrays in these languages with the same logic as Python.
Common mistakes include ignoring array length differences, failing to account for even-length arrays, or not handling empty arrays. Proper index calculations and understanding array partitioning are critical when learning to find the median of two sorted arrays.
To verify, you can merge both arrays fully and check that the computed median matches the central value(s). Ensuring that left elements are smaller than right elements in partition-based methods guarantees correct results for finding the median of two sorted arrays.
Yes, multi-array median computation is possible, though it requires careful merging or multi-array partitioning. Extending the principles used to find the median of two sorted arrays can handle multiple arrays, but algorithmic complexity increases and efficiency considerations become more important.
FREE COURSES
Start Learning For Free
Author|900 articles published