Leetcode Median of two Sorted arrays in Python and Golang

A New Day of Leetcode and Unemployment Woes

Hello Everyone!
Today marks yet another bright, valuable, and—let’s be honest—mentally exhausting day of being unemployed. Yes, it’s one of those phases where reality hits you hard and forces you to face the very thing you’ve been avoiding for years: Leetcode.

Back in my college days, I always managed to steer clear of Leetcode. It was like that gym membership you keep paying for but never use. Even after working for a year as a developer, I never really saw the need for it. But now, with resignation giving me an abundance of free time, I had no more excuses left. The coding grind was inevitable.

As mentioned in my previous Leetcode blog, where I tackled the famous Two Sum problem (👈 click here to check that out), I’ve decided to keep the momentum going.


To keep things interesting (and mildly frustrating), I filtered problems by Arrays and somehow landed in the land of Hard problems. The chosen one today?

4. Median of Two Sorted Arrays

This problem wants us to return the median of two arrays—these arrays can be of equal or different sizes. Thankfully, the problem gives us a little help: both arrays are already sorted.

Sounds easy? Well, not really. Especially when your brain is still recovering from the trauma of interviews and job hunts.


Problem Understanding

Here’s the simple understanding I gathered from reading and re-reading the problem statement (with a cup of tea and self-doubt):

We’re given two sorted arrays. We need to find the median of the combined array. Depending on the total length (even or odd), the median rules vary:

  1. Even Length: If the combined array has an even number of elements, we add the two middle values, divide them by 2, and return a float.

  2. Odd Length: If the length is odd, we simply return the middle value.

Pretty straightforward, right? Well, let’s see how I coded this.


My Python Solution 🐍

Starting with what I’m most comfortable with, I wrote the solution in Python:

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        nums1.extend(nums2)
        nums1.sort()
        tota=len(nums1)
        if tota %2 == 0:
            return (nums1[tota //2] + nums1[(tota //2) - 1])/2
        else:
            return nums1[tota //2]
       

Let me break this down for those who might be starting out:

  • First, I extended nums1 with nums2. This merges the second list into the first one. In Python, .extend() is great because lists are mutable.

  • Then, I sorted the combined list using .sort().

  • I stored the length in a variable tota.

  • Finally, I used the even/odd logic discussed earlier to return the median.

Time: 0 ms
Memory: 18.1 MB

Pretty efficient for a brute-force solution!


Now in Golang 🦫

Since I’ve been learning Golang recently (because why not add more stress during unemployment), I decided to try the same logic in Go.

func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
    nums1=append(nums1,nums2...)
    sort.Ints(nums1)
    val:=len(nums1)
    if(val %2 == 0){
        return float64(nums1[val/2-1]+nums1[val/2]) / 2
    }
    return float64(nums1[val/2])
}

And again, line by line:

  • We append nums2 to nums1 using Go’s built-in append function with ... to spread values.

  • Used sort.Ints() to sort the combined array.

  • Got the length using len().

  • Followed the same even/odd logic for returning the median.

Time: 0 ms
Memory: 7.1 MB

Golang is super fast and memory-efficient. I love how minimal and clean the syntax is once you get used to the strict typing.


Some Observations

  • Both solutions work, but Python gives us the freedom to write less and do more.

  • Golang, on the other hand, forces you to be disciplined, which can be a good thing when you want performance and control.

  • In both cases, I’ve used the simplest approach possible—merge + sort + find median. Of course, there are more optimized solutions using binary search with a time complexity of O(log(min(n, m))), but I’ll save that for another headache day 😅.


Post a Comment

0 Comments