When implementing operations that manipulate collections or perform repeated actions, carefully consider the time complexity implications. Avoid operations that could result in unexpected quadratic or worse complexity. Pay special attention to:
When implementing operations that manipulate collections or perform repeated actions, carefully consider the time complexity implications. Avoid operations that could result in unexpected quadratic or worse complexity. Pay special attention to:
Example of problematic implementation:
// BAD: O(n²) complexity
fun <E> ArrayList<E>.addAll(index: Int, elements: Collection<E>) {
var i = index
elements.forEach { element ->
array.asDynamic().splice(i, 0, element) // Shifts array on each insert
i++
}
}
// BETTER: O(n) complexity
fun <E> ArrayList<E>.addAll(index: Int, elements: Collection<E>) {
// Single array modification with all elements
array.asDynamic().splice(index, 0, *elements.toTypedArray())
}
Choose data structures based on your specific use case:
Enter the URL of a public GitHub repository