Skip to content
Advertisement

Kotlin single equal sign “=” object assignment time complexity

What is the time complexity of object assignment using the equals sign in Kotlin (or Java)?

fun moveZeroes(nums: IntArray): Unit {
    var numsCopy = nums
}

More specifically if I have my own object ListNode

 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */

What would be the copy time below?

fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
    var l1Copy = l1
}

I find myself often doing this assignment since ListNode passes as val, and I can’t do

l1 = l1?.next

Advertisement

Answer

The assignment

var l1Copy = l1

does not make a new ListNode object that contains the same properties as l1. It just creates a new variable called l1Copy and points it to the same memory location as l1, so it’s an O(1) operation.

In the following code

fun f(n: ListNode) {
    var n1 = n
}

val node = ListNode(1)
val var1 = node
f(node)

there’s only one object, ListNode(1), and three variables pointing to it: node and var1 in the global scope, and n and n1 in f‘s scope.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement