Start learning free

LESSON 230 OF 291 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Lists to a Dictionary in Kotlin: Pairing by Index

Practice Read the full explanation

Given an array of strings names and an array of integers scores of the same length, pair each name with the score at the same index. Return a HashMap where names[i] is a key and scores[i] is its value.

The names are all different, while two names can have the same score. If names and scores are empty, return an empty HashMap. The order of the entries doesn't matter.

Example 1:

Input: names = ["Ana", "Ben", "Cara"], scores = [90, 75, 88]
Output: {"Ana": 90, "Ben": 75, "Cara": 88}
Explanation: "Ana" is at index 0 in names, and the score at index 0 is 90. The same goes for "Ben" with 75 and "Cara" with 88.

Example 2:

Input: names = ["Zoe", "Adam"], scores = [60, 60]
Output: {"Zoe": 60, "Adam": 60}
Explanation: Two names with the same score are two different entries.

Example 3:

Input: names = ["Max"], scores = [100]
Output: {"Max": 100}
Explanation: One name gives a single entry.
STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in Kotlin, explained

    Problem overview

    The function toDictionary receives an array of names and an IntArray of scores with the same length. It returns a map where each names[i] is a key and scores[i] is its value. For names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88] the map is {Ana=90, Ben=75, Cara=88}. Names are all different, two names may share a score, and empty inputs give an empty map.

    Approach: one index reaches both

    A name and its score sit at the same position in their arrays, so a loop over the positions can read both with the same index. Each pass adds one entry to a map that started empty.

    Step by step

    1. Create the empty map result with mutableMapOf<String, Int>(): names as keys, scores as values.
    2. Loop over the indexes. 0 until names.size is the range 0, 1, ... up to the last valid index. The upper end is excluded.
    3. Add the pair. result[names[i]] = scores[i] stores the score under the name.
    4. Return result after the loop.

    The solution in Kotlin

    class Solution {
        fun toDictionary(names: Array<String>, scores: IntArray): MutableMap<String, Int> {
            val result = mutableMapOf<String, Int>()
            for (i in 0 until names.size) {
                result[names[i]] = scores[i]
            }
            return result
        }
    }
    

    Kotlin details worth knowing:

    • until versus ... 0 until 3 covers 0, 1 and 2. 0..3 includes 3 and would read one element too far, which throws an ArrayIndexOutOfBoundsException.
    • indices. for (i in names.indices) is the idiomatic way to write the same range, and it stays correct if the array changes.
    • Assigning to a missing key adds it. No check is needed first. If the key exists, the assignment replaces its value.
    • Two arrays of different kinds. Array<String> holds objects, while IntArray holds primitive integers. Both are indexed with [i].
    • Empty input. With empty arrays, the range 0 until 0 is empty, the loop doesn't run, and the function returns an empty map, printed as {}.

    Tracing the loop

    For names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the map after each index is:

    i=0 -> {Ana=90}
    i=1 -> {Ana=90, Ben=75}
    i=2 -> {Ana=90, Ben=75, Cara=88}

    The same index i picks the name from one array and the score from the other. Kotlin's standard library can do the pairing and the map in one expression, names.zip(scores.toList()).toMap(), which gives the same {Ana=90, Ben=75, Cara=88}. The toList() is needed because zip on an Array accepts another array or a list, but not an IntArray.

    Edge cases and common mistakes

    • Same score. ["Zoe", "Adam"] with [60, 60] gives two entries. Only duplicate keys collide, and duplicate values are fine.
    • Duplicate names. The lesson promises none. If a name did repeat, the later score would replace the earlier one: ["Ana", "Ana"] with [1, 2] gives {Ana=2}.
    • Off-by-one. 0..names.size reads past the end. Use until.
    • Swapping the roles. The names are the keys. Using scores as keys would lose entries whenever two scores match.

    Why a map fits

    Scores are looked up by name, and a map answers "what is Ben's score?" directly with result["Ben"], without searching through the two arrays. Note that this lookup returns Int?: it is null for a name that isn't in the map. The two arrays have no such protection, and asking an array for an index past its end throws an exception instead.

    Testing

    • ["Ana", "Ben", "Cara"] with [90, 75, 88] gives {Ana=90, Ben=75, Cara=88}.
    • ["Zoe", "Adam"] with [60, 60] gives {Zoe=60, Adam=60}.
    • ["Max"] with [100] gives {Max=100}.
    • Two empty arrays give {}.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free