DEV Community

Discussion on: LeetCode: Majority Element

Collapse
 
johnmilimo profile image
JMW

Solution in KOTLIN with a single pass, O(n), through the array:

fun majorityElement(elements: Array<Int>): Int? {
    val freq = mutableMapOf<Int, Int>()
    val majorityCount = elements.count() / 2
    var majorityElement: Int? = null
    elements.forEach { element ->
        val count = freq.getOrDefault(element, 0) + 1
        if(count > majorityCount) {
            majorityElement = element
            return@forEach
        }
        freq[element] = count
    }
    return majorityElement
}