Character (string) type in R Programming - Time & Space Complexity
When working with character strings in R, it is important to understand how the time to process them changes as the string gets longer.
We want to know how the time to handle strings grows when the string size increases.
Analyze the time complexity of the following code snippet.
# Count the number of vowels in a string
count_vowels <- function(text) {
vowels <- c('a', 'e', 'i', 'o', 'u')
count <- 0
for (char in strsplit(text, NULL)[[1]]) {
if (char %in% vowels) {
count <- count + 1
}
}
return(count)
}
This code counts how many vowels are in a given string by checking each character one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the input string.
As the string gets longer, the code checks more characters one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The number of operations grows directly with the string length.
Time Complexity: O(n)
This means the time to count vowels grows in a straight line as the string gets longer.
[X] Wrong: "Checking each character is constant time no matter the string length."
[OK] Correct: Each character must be checked one by one, so more characters mean more work.
Understanding how string length affects processing time helps you write efficient code and explain your reasoning clearly in interviews.
"What if we used a built-in function that counts vowels without looping explicitly? How would the time complexity change?"