0
0
Kotlinprogramming~5 mins

Nullable types with ? suffix in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nullable types with ? suffix
O(n)
Understanding Time Complexity

We want to understand how using nullable types with the ? suffix affects the time it takes for a program to run.

Specifically, does checking for null add extra work as the input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

fun printLengths(strings: List) {
    for (str in strings) {
        if (str != null) {
            println(str.length)
        } else {
            println("Null string")
        }
    }
}

This code goes through a list of strings that can be null and prints their length or a message if null.

Identify Repeating Operations
  • Primary operation: Looping through each item in the list once.
  • How many times: Exactly once per item in the list.
How Execution Grows With Input

As the list gets bigger, the program checks each item once, whether it is null or not.

Input Size (n)Approx. Operations
10About 10 checks and prints
100About 100 checks and prints
1000About 1000 checks and prints

Pattern observation: The work grows directly with the number of items. More items mean more checks and prints.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items in the list.

Common Mistake

[X] Wrong: "Checking for null makes the program slower in a way that depends on how many nulls there are."

[OK] Correct: The program always checks each item once, no matter if it is null or not. The number of nulls does not change how many times it checks.

Interview Connect

Understanding how nullable types affect performance helps you write clear and efficient Kotlin code, a useful skill in many coding situations.

Self-Check

What if we replaced the list with a nested list of nullable strings? How would the time complexity change?