Numeric and character vectors in R Programming - Time & Space Complexity
When working with numeric and character vectors in R, it is important to understand how the time to process them grows as their size increases.
We want to know how the number of steps changes when we do operations on these vectors.
Analyze the time complexity of the following code snippet.
# Create numeric vector
num_vec <- 1:1000
# Create character vector
char_vec <- as.character(num_vec)
# Convert numeric vector to character vector
result <- as.character(num_vec)
# Concatenate two character vectors
combined <- c(char_vec, result)
This code creates numeric and character vectors, converts numeric to character, and combines two character vectors.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Converting each element of the numeric vector to a character string.
- How many times: Once for each element in the vector (n times).
- Secondary operation: Concatenating two character vectors, which involves copying elements.
- How many times: Proportional to the total length of both vectors (about 2n elements copied).
As the vector size grows, the number of operations grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 conversions + 20 concatenations |
| 100 | About 100 conversions + 200 concatenations |
| 1000 | About 1000 conversions + 2000 concatenations |
Pattern observation: The total steps increase roughly in a straight line as input size grows.
Time Complexity: O(n)
This means the time to run the code grows directly with the size of the vectors.
[X] Wrong: "Converting or combining vectors takes the same time no matter how big they are."
[OK] Correct: Each element must be processed, so bigger vectors take more time.
Understanding how vector operations scale helps you write efficient R code and explain your reasoning clearly in interviews.
"What if we used a list instead of a vector? How would the time complexity change?"