Char type and Unicode behavior in Kotlin - Time & Space Complexity
We want to understand how operations with Kotlin's Char type and Unicode characters affect the time it takes to run code.
Specifically, how does processing characters scale when dealing with Unicode?
Analyze the time complexity of the following code snippet.
fun countUppercase(chars: List): Int {
var count = 0
for (c in chars) {
if (c.isUpperCase()) {
count++
}
}
return count
}
This code counts how many uppercase characters are in a list of characters, considering Unicode rules.
- Primary operation: Looping through each character in the list once.
- How many times: Exactly once per character, so as many times as the list size.
As the number of characters grows, the code checks each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 character checks |
| 100 | 100 character checks |
| 1000 | 1000 character checks |
Pattern observation: The work grows directly with the number of characters.
Time Complexity: O(n)
This means the time to count uppercase characters grows linearly with the number of characters.
[X] Wrong: "Checking if a character is uppercase takes constant time regardless of Unicode complexity."
[OK] Correct: Some Unicode characters require more work to check case, but Kotlin handles this internally, so the overall loop still runs once per character.
Understanding how character processing scales helps you write efficient text handling code, a common task in many programs.
"What if we changed the input from a List<Char> to a String? How would the time complexity change?"