Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Reverse

reversed() function returns the reverse of the string :

 fun String.reversed(): String
 

We can implement this function in two ways :

In-place swapping

Recall that String is immutable, so for modifications we have to first convert it to CharArray. Array is mutable, so we can perform in-place swapping in order to reverse it. In-place means we modify the same CharArray using swaps and need not create any new CharArray.

Algorithm

To reverse an array, we can swap the first half elements of the array with the second half elements of the array. First element from start will be swapped with first element from the end, second element from the start will be swapped with second element from the end, so on and so forth. This way for an array of n elements, we have to perform n/2 iterations and on each iteration, we swap ith element with (n-1-i)^^th^^ element.

Implementation

 fun String.reversedUsingSwap(): String {
    val array = toCharArray()

    for (i in 0 until (array.size / 2)) {
        array[i] = array[array.lastIndex - i].apply {
            array[array.lastIndex - i] = array[i]
        }
    }

    return array.concatToString()
}
 

This works for both even and odd lengths of string. For example,

  • if length is 2 (even), we perform 2/2 = 1 iteration i.e. 0 until 1
  • if length is 5 (odd), we perform 5/2 = 2 iteration i.e. 0 until 2

Using new array

Another approach to reverse a string is to iterate it in the reverse order and add the elements to a new array.

Algorithm

  • Create a new CharArray of length same as that of input string
  • Iterate over the string in reverse order i.e. lastIndex..0 or indices.reversed()
  • On ith iteration, copy array[i] to newArray[lastIndex - i]. Example - array’s lastIndex element will be copied at lastIndex - lastIndex i.e. 0th position of the new array.

Implementation

 fun String.reversedUsingNewArray(): String {
    val array = toCharArray()

    val newArray = CharArray(length)
    for (i in indices.reversed()) {
        newArray[lastIndex - i] = array[i]
    }

    return newArray.concatToString()
}
 

Note that this approach is not memory efficient because it requires us to create new array of the same size as of input.