Hey everyone! Mahdi Shamlou here — continuing my LeetCode classic problems series.
After [Longest Substring Without Repeating Characters], today we’re looking at Problem #4 — Median of Two Sorted Arrays — one of the famous hard ones!
Problem Statement
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Examples:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.0
-----
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5
-----
Input: nums1 = [], nums2 = [2,3]
Output: 2.50000
My first intuitive solution (the fun & lazy way I tried) This is exactly what came to my mind when I first saw it — just throw everything together:
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
list3 = nums1 + nums2 # just combine them
list3 = sorted(list3) # sort everything
mid = len(list3) / 2
print(list3) # I even printed to see what happens 😂
print(f'mid is {mid}')
if len(list3) % 2 == 0: # even number of elements
return (list3[int(mid)] + list3[int(mid)-1]) / 2
else: # odd
return list3[int(mid)]
It works, it’s super readable, and honestly — for small inputs — it feels very satisfying to write 😄
My repo (all solutions are here): GitHub — mahdi0shamlou/LeetCode: Solve LeetCode Problems
What about you? How did you first approach this problem? Did you also just merge + sort at the beginning like me? 😅 Or did you go straight to something else?
And honestly… after finally getting this naive version to pass all test cases, I just sat back, laughed at how simple (yet not-so-efficient) it was, and felt that sweet mix of relief and “I did it!” energy 😂 Here’s me right after hitting “Submit”:
Share in the comments — I read everything! 🚀
Connect with me:
🔗 LinkedIn: https://www.linkedin.com/in/mahdi-shamlou-3b52b8278
📱 Telegram: https://telegram.me/mahdi0shamlou
📸 Instagram: https://www.instagram.com/mahdi0shamlou/
Author: Mahdi Shamlou | مهدی شاملو


Top comments (0)