Parsing and Manipulating Nested Maps in Kotlin

Introduction

Hello, and welcome back! Are you ready for a new challenge? In this unit, we're exploring an interesting task using Kotlin's powerful map capabilities. We'll be focusing on parsing complex strings into nested maps and updating them. This is a common requirement in many real-world tasks, making our session particularly practical — just the way you like it!

Task Statement

This task involves transforming a given string into a nested map and updating a specific key-value pair within that map using Kotlin. The input string will take the form "Key1=Value1,Key2=Value2,...". When a part of the value is another key-value string, we create a nested map.

For example, the string "A1=B1,C1={D1=E1,F1=G1},I1=J1" should be transformed into the following nested map:

val dictionary: MutableMap<String, Any> = mutableMapOf(
    "A1" to mutableMapOf("" to "B1"),
    "C1" to mutableMapOf("D1" to "E1", "F1" to "G1"),
    "I1" to mutableMapOf("" to "J1")
)

Your function should parse this string into the above nested map, then update the value of the nested key F1 from G1 to another value, say NewValue. The function should ultimately return the updated map.

Step 1 - Setting Up the Function and Variables

First, set up the function and necessary variables in Kotlin:

fun parseString(inputString: String): MutableMap<String, Any> {
    val result = mutableMapOf<String, Any>() // Stores the final nested map structure with parsed key-value pairs.
    var key = "" // Temporarily holds the current key being parsed from the input string.
    var innerMap = mutableMapOf<String, String>() // Temporarily holds key-value pairs for any detected inner map.
    var inInnerMap = false // Flag to indicate whether the parsing process is currently inside an inner map.
    var i = 0 // Index used to iterate through each character of the input string.

Step 2 - Handling the Opening and Closing Braces

Next, handle the opening and closing braces. If an inner map is encountered, set the flag and prepare to parse it:

    while (i < inputString.length) {
        when (inputString[i]) {
            '{' -> {
                // Entering an inner map
                inInnerMap = true
                i++ // Skip the '{'
            }
            '}' -> {
                // Exiting an inner map
                result[key] = innerMap
                innerMap = mutableMapOf()
                inInnerMap = false
                i++ // Skip the '}'
                if (i < inputString.length && inputString[i] == ',') {
                    i++ // Skip the ',' after '}'
                }
            }
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal