Reversing Words in a String Using Kotlin: A Detailed Guide

Table of Contents

Reversing words in a sentence is a common programming task often used in coding interviews and algorithm-based challenges. In this blog, we’ll break down a Kotlin function that reverses the order of words in a given string. We’ll analyze each part of the code, identify potential improvements, and present an optimized version.

Reversing Words: Problem Statement

Given an input string containing multiple words separated by spaces, we need to reverse the order of words while maintaining their original form.

Input:

Kotlin
"Hello India Pune World"

Output:

Kotlin
"World Pune India Hello"

Understanding the Kotlin Code

Let’s analyze the following Kotlin function that reverses the order of words in a string:

Kotlin
fun reverseInputStatement(input: String): String {
    val wordList = input.split(" ")
    val mutableWordList = wordList.toMutableList()
    
    var indexFromEnd = mutableWordList.size - 1
    
    for (indexFromStart in mutableWordList.indices) {
        if (indexFromStart < indexFromEnd) {
            val temp = mutableWordList[indexFromStart]
            mutableWordList[indexFromStart] = mutableWordList[indexFromEnd]
            mutableWordList[indexFromEnd] = temp
        }
        indexFromEnd -= 1
    }
    
    return mutableWordList.toString()
}

Step-by-Step Breakdown

Step 1: Splitting the Input String into Words

Kotlin
val wordList = input.split(" ")
  • The split(" ") function divides the input string into a list of words based on spaces.
  • For the input “Hello India Pune World”, the output will be:
  • ["Hello", "India", "Pune", "World"]

Step 2: Converting to a Mutable List

Kotlin
val mutableWordList = wordList.toMutableList()   
  • Since lists in Kotlin are immutable by default, we convert it to a mutable list to allow modifications.

Step 3: Swapping Words to Reverse Their Order

Kotlin
var indexFromEnd = mutableWordList.size - 1
  • indexFromEnd is initialized to the last index of the list.

The loop performs word swaps to reverse the order:

Kotlin
for (indexFromStart in mutableWordList.indices) {
    if (indexFromStart < indexFromEnd) {
        val temp = mutableWordList[indexFromStart]
        mutableWordList[indexFromStart] = mutableWordList[indexFromEnd]
        mutableWordList[indexFromEnd] = temp
    }
    indexFromEnd -= 1
}

Here,

  • The loop iterates through the list from both the beginning (indexFromStart) and the end (indexFromEnd).
  • The words are swapped until they meet in the middle.

Here is the how the list changes at each iteration:

Before swapping: ["Hello", "India", "Pune", "World"]

  • Step 1: Swap Hello and World["World", "India", "Pune", "Hello"]
  • Step 2: Swap India and Pune["World", "Pune", "India", "Hello"]

Loop stops as words are fully reversed.

Step 4: Converting Back to a String

Kotlin
return mutableWordList.toString()

This returns the reversed list, but the output will be formatted as:

Kotlin
[World, pune, india, Hello]

This isn’t a properly formatted sentence, so let’s fix this issue.

Optimizing the Code

The existing function works, but it can be significantly simplified using Kotlin’s built-in functions:

Kotlin
fun reverseInputStatement(input: String): String {
    return input.split(" ").reversed().joinToString(" ")
}

Why is This Better?

  • split(" "): Splits the input string into a list of words.
  • reversed(): Reverses the list.
  • joinToString(" "): Joins the list back into a properly formatted string.
  • More readable and concise compared to manually swapping elements.

Final Output

For the input:

Kotlin
"Hello India Pune World"

The output will be:

Kotlin
"World Pune India Hello"

Key Takeaways

  1. Use Kotlin’s built-in functions (split(), reversed(), joinToString()) for cleaner and more efficient code.
  2. Avoid unnecessary manual swapping unless specifically required.
  3. Understand how lists work — mutable and immutable lists impact how you modify data in Kotlin.
  4. Code readability is important — the optimized version is much easier to understand and maintain.

Conclusion

Reversing words in a string is a simple yet insightful exercise in Kotlin. The initial approach using a loop and swapping elements works but is not the most efficient solution. By leveraging Kotlin’s built-in functions, we can achieve the same result with cleaner and more readable code.

Understanding such basic transformations is crucial for improving problem-solving skills, especially in coding interviews and real-world applications.

Skill Up: Software & AI Updates!

Receive our latest insights and updates directly to your inbox

Related Posts

error: Content is protected !!