Skip to content

Latest commit

 

History

History
22 lines (20 loc) · 734 Bytes

File metadata and controls

22 lines (20 loc) · 734 Bytes

We can create a count array which required O(n) space, but there is optimal way that does not require O(n) space.

fun commonChars(words: Array<String>): List<String> {
    val countResult = IntArray(26) { Int.MAX_VALUE }
    val result = mutableListOf<String>()
    for (word in words) {
        val count = IntArray(26)
        for (c in word) count[c - 'a']++
        for (i in 0 until 26) {
            countResult[i] = min(countResult[i], count[i])
        }
    }   
    for (i in 0 until 26) {
        for (c in 0 until countResult[i])
            result.add(('a' + i).toString())
    }
    return result
}