Majority Element

Writing code in Kotlin brings so much fun particularly when solving Leetcode problems such as this one.

class Solution {
    fun majorityElement(nums: IntArray): Int {        
        val half = nums.size / 2
        return nums.groupBy { it }.filter {
            it.value.size > half
        }.map { it.key }.last()
    }
}
Runtime: 240 ms, faster than 42.58% of Kotlin online submissions for Majority Element.
Memory Usage: 41.3 MB, less than 100.00% of Kotlin online submissions for Majority Element.

See how short the code is? And I think it’s also very easy to understand. Although I think we could still improve the performance by simply using for-loops instead of operators.