How to find the shortest identical consecutive subarray in an array with Kotlin

1 Answer

0 votes
fun shortest_identical_consecutive_subarray(arr: IntArray): IntArray {
    if (arr.isEmpty()) return intArrayOf()

    var bestStart = 0
    var bestLen = arr.size

    var currentStart = 0
    var currentLen = 1

    for (i in 1 until arr.size) {
        if (arr[i] == arr[i - 1]) {
            currentLen++
        } else {
            if (currentLen < bestLen) {
                bestLen = currentLen
                bestStart = currentStart
            }
            currentStart = i
            currentLen = 1
        }
    }

    if (currentLen < bestLen) {
        bestLen = currentLen
        bestStart = currentStart
    }

    return arr.copyOfRange(bestStart, bestStart + bestLen)
}

fun main() {
    val arr = intArrayOf(
        3,3,3,
        7,7,7,7,7,
        2,2,
        5,5,5,5,
        9,9,9,9,9,9
    )

    val resultArr = shortest_identical_consecutive_subarray(arr)

    print("Array result: ")
    resultArr.forEach { print("$it ") }
}




/*
run:

Array result: 2 2 

*/

 



answered Feb 9 by avibootz

Related questions

...