Minimum Index Sum of Two Lists

The solution for this problem is to loop through any of the list and each time a word exists in both lists, then get the sum of their indexes and use that as the key to store the word in a hashmap. Also, keep track of the lowest key of the map so that later on, you can use that to return the answer.

class Solution {
    fun findRestaurant(list1: Array<String>, list2: Array<String>): Array<String> {
        val output = HashMap<Int, ArrayList<String>>()
        var lowest = Integer.MAX_VALUE
        
        for(index in list1.indices){
            var i = list2.indexOf(list1[index]) 
            if(i != -1) {
                i = i + index 
                output.putIfAbsent(i, ArrayList())
                output[i]?.add(list1[index])
                lowest = Math.min(lowest, i)
            }
        }
        
        return output[lowest]!!.toTypedArray()
    }
}
Runtime: 320 ms, faster than 57.89% of Kotlin online submissions for Minimum Index Sum of Two Lists.
Memory Usage: 38 MB, less than 100.00% of Kotlin online submissions for Minimum Index Sum of Two Lists.
comments powered by Disqus