C++ 0004.cpp
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> both = nums1;
both.insert(both.end(), nums2.begin(), nums2.end());
sort(both.begin(), both.end());
int mid = both.size() / 2;
if (both.size() % 2 == 0)
return (double(both[mid-1]) + both[mid]) / 2;
else
return both[mid];
}
};
Difficulty
and has an acceptance rate of about 47% (9+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Divide And Conquer
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single public method findMedianSortedArrays. The method receives two integer vectors that are already sorted individually. It produces a single double value representing the median of the combined multiset of elements from both vectors. The approach taken is to create a new container that holds all elements, sort the combined collection, and then extract the median based on the total count’s parity.
Key Steps
The algorithm proceeds through a clear sequence of operations, each reflected in a concise code fragment.
The first step creates a copy of the first input vector, establishing the base of the merged collection:
vector<int> both = nums1;
Next, the elements of the second vector are appended to the end of the copy. The insert call efficiently extends the container without the need for manual looping:
both.insert(both.end(), nums2.begin(), nums2.end());
With all values now present in a single vector, the method sorts the combined data. The standard library sort algorithm is invoked, which internally selects an optimal hybrid sorting strategy for the given data size and type:
sort(both.begin(), both.end());
After sorting, the midpoint index is calculated by integer division of the total size. This index serves as the anchor for median extraction:
int mid = both.size() / 2;
The final stage distinguishes between even and odd total lengths. For an even count, the median is the arithmetic mean of the two central elements; for an odd count, it is simply the central element. The code expresses both cases directly:
if (both.size() % 2 == 0)
return (double(both[mid-1]) + both[mid]) / 2;
else
return both[mid];
Edge Cases Handled
The implementation gracefully manages scenarios where one or both input vectors are empty. By copying the first vector and then inserting the second, the resulting both vector correctly reflects the union of any combination of empty and non-empty inputs. The subsequent sorting step operates safely on an empty or singleton vector, as the standard sort algorithm is defined for zero or one element ranges.
When the combined size is even, the code accesses both[mid-1] and both[mid]. Because mid is derived from integer division, mid-1 is guaranteed to be a valid index for any even-sized collection with at least two elements. For an odd-sized collection, the direct return of both[mid] yields the exact middle element without additional computation.
The conversion to double in the even case ensures that the division yields a floating-point result, preserving fractional medians such as 2.5. In the odd case, the integer element is implicitly converted to double by the function’s return type, delivering a consistent numeric type for all outcomes.
Performance Optimizations
Although the algorithm follows a straightforward merge-and-sort strategy, it leverages several standard-library facilities that contribute to efficient execution. The initial copy of nums1 into both utilizes the vector copy constructor, which performs a bulk memory copy when possible, reducing overhead compared to element-wise insertion.
The insert operation appends an entire range in a single call. Internally, the vector may reallocate once to accommodate the additional elements, minimizing the number of memory allocations and copies required.
Sorting is delegated to std::sort, which typically implements introsort-a hybrid of quicksort, heapsort, and insertion sort. This choice adapts to the data’s characteristics, providing fast average-case performance while guarding against pathological worst-case scenarios without additional programmer effort.
Finally, the median extraction avoids any extra passes over the data. By computing the midpoint index once and using direct element access, the method eliminates unnecessary loops or conditional traversals, keeping the post-sort work to a constant amount of operations.
ELI5 - Simplified Explanation
Imagine two collections of colorful building blocks, each already placed in a neat, straight line from smallest to biggest. The first part of this code takes all the blocks from the first line and adds them to the end of the second line, creating one long, mixed-up line. Since the new line is jumbled, the code uses a special trick to rearrange every block until they are all back in order, from the tiny ones at the start to the giant ones at the end.
Once all the blocks are lined up perfectly, the code looks for the very middle of the path. If the total number of blocks is an odd count, the middle block is exactly the answer. If there is an even total count of blocks, there will be two blocks sitting right in the center. In that case, the code grabs both of those center blocks and finds the halfway point between them to decide the final result.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||||
| WalkCCC | C++ | Python | Java | ||||||||||||
| leetcode.ca | C++ | Python | Java | C# | JS | Go | C | Nim | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||||
| Progiez | C++ | Python | Java | ||||||||||||
| github | aylei | Rust | |||||||||||||
| begeekmyfriend | C | ||||||||||||||
| BigEggStudy | C# | ||||||||||||||
| black-shadows | C++ | ||||||||||||||
| bujosa | Rust | ||||||||||||||
| chandansgowda | Python | ||||||||||||||
| charles-wangkai | Java | ||||||||||||||
| chenyanzhe | C++ | ||||||||||||||
| everthis | JS | ||||||||||||||
| fartem | Ruby | ||||||||||||||
| FelixFan1122 | C# | ||||||||||||||
| fengvyi | C++ | ||||||||||||||
| fpdjsns | C++ | ||||||||||||||
| fsq | C++ | ||||||||||||||
| gaosq0604 | Python | ||||||||||||||
| Garvit244 | Python | ||||||||||||||
| gouthampradhan | Java | ||||||||||||||
| halfrost | Go | ||||||||||||||
| haoel | C++ | ||||||||||||||
| JoshCrozier | JS | ||||||||||||||
| keineahnung2345 | C++ | ||||||||||||||
| lkwq007 | Python | ||||||||||||||
| luangong | C++ | ||||||||||||||
| MacJim | C++ | ||||||||||||||
| muhammadfarhankt | Go | ||||||||||||||
| qiyuangong | Java | ||||||||||||||
| ruoru | Rust | ||||||||||||||
| Shamik07 | Dart | ||||||||||||||
| shreymehul | C# | ||||||||||||||
| sonugiri1043 | C++ | ||||||||||||||
| suxrobGM | C# | ||||||||||||||
| varunu28 | Java | ||||||||||||||
| vli02 | C | ||||||||||||||
| wisdompeak | C++ | ||||||||||||||
| yuanliu666 | Kotlin | ||||||||||||||
| YuriSpiridonov | Python | ||||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, Nim, PHP, Python, TypeScript | ||||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||||
| Progiez | C++, Java, Python | ||||||||||||||
| aylei | Rust | ||||||||||||||
| begeekmyfriend | C | ||||||||||||||
| BigEggStudy | C# | ||||||||||||||
| black-shadows | C++, C++ | ||||||||||||||
| bujosa | Rust | ||||||||||||||
| chandansgowda | Python | ||||||||||||||
| charles-wangkai | Java | ||||||||||||||
| chenyanzhe | C++ | ||||||||||||||
| everthis | JavaScript | ||||||||||||||
| fartem | Ruby | ||||||||||||||
| FelixFan1122 | C# | ||||||||||||||
| fengvyi | C++ | ||||||||||||||
| fpdjsns | C++ | ||||||||||||||
| fsq | C++ | ||||||||||||||
| gaosq0604 | Python | ||||||||||||||
| Garvit244 | Python | ||||||||||||||
| gouthampradhan | Java | ||||||||||||||
| halfrost | Go | ||||||||||||||
| haoel | C++ | ||||||||||||||
| JoshCrozier | JavaScript | ||||||||||||||
| keineahnung2345 | C++ | ||||||||||||||
| lkwq007 | Python | ||||||||||||||
| luangong | C++ | ||||||||||||||
| MacJim | C++ | ||||||||||||||
| muhammadfarhankt | Go | ||||||||||||||
| qiyuangong | Java | ||||||||||||||
| ruoru | Rust | ||||||||||||||
| Shamik07 | Dart | ||||||||||||||
| shreymehul | C# | ||||||||||||||
| sonugiri1043 | C++ | ||||||||||||||
| suxrobGM | C# | ||||||||||||||
| varunu28 | Java | ||||||||||||||
| vli02 | C | ||||||||||||||
| wisdompeak | C++ | ||||||||||||||
| yuanliu666 | Kotlin | ||||||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2387: Median of a Row Wise Sorted Matrix
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality