sub and gsub in R Programming - Time & Space Complexity
We want to understand how the time it takes to replace text grows when using sub and gsub in R.
How does the work change as the text gets longer or has more matches?
Analyze the time complexity of the following code snippet.
text <- c("apple apple", "banana apple", "apple banana apple")
result_sub <- sub("apple", "orange", text)
result_gsub <- gsub("apple", "orange", text)
This code replaces the first occurrence of "apple" with "orange" using sub, and all occurrences using gsub, in a vector of strings.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each string to find matches of the pattern.
- How many times: For
sub, scanning stops after the first match per string; forgsub, scanning continues through the entire string to find all matches.
As the length of each string or the number of strings grows, the work increases.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (short strings) | About 10 scans for sub, 10 full scans for gsub |
| 100 (longer strings) | About 100 scans for sub, 100 full scans for gsub |
| 1000 (many long strings) | About 1000 scans for sub, 1000 full scans for gsub |
Pattern observation: The time grows roughly in direct proportion to the total length of all strings. gsub does more work per string because it finds all matches, not just the first.
Time Complexity: O(n)
This means the time to replace text grows linearly with the total size of the input strings.
[X] Wrong: "sub and gsub always take the same time because they do similar replacements."
[OK] Correct: sub stops after the first match in each string, so it often does less work than gsub, which finds and replaces all matches.
Understanding how string replacement scales helps you write efficient code when working with text data, a common task in many projects.
"What if we changed the pattern to a more complex regular expression? How would the time complexity change?"
Practice
sub and gsub in R?Solution
Step 1: Understand
subbehaviorsubreplaces only the first occurrence of the pattern in the string.Step 2: Understand
gsubbehaviorgsubreplaces all occurrences of the pattern in the string.Final Answer:
subreplaces only the first match,gsubreplaces all matches. -> Option CQuick Check:
sub= first match,gsub= all matches [OK]
- Confusing which function replaces all matches
- Thinking sub modifies original string in place
- Assuming gsub only replaces first match
sub?Solution
Step 1: Identify correct function and parameters
subtakes pattern, replacement, and the string in that order.Step 2: Check the parameters match the question
We want to replace "cat" with "dog" in "cat and cat" usingsub.Final Answer:
sub("cat", "dog", "cat and cat") -> Option AQuick Check:
Correct syntax with sub and parameters [OK]
- Swapping pattern and replacement arguments
- Using gsub instead of sub for first occurrence
- Using a non-existent function like replace
text <- "apple apple apple"
result <- sub("apple", "orange", text)
print(result)Solution
Step 1: Understand
The first "apple" in the string is replaced by "orange".subreplaces first match onlyStep 2: Apply replacement to the string
Result becomes "orange apple apple" because only the first "apple" changes.Final Answer:
"orange apple apple" -> Option BQuick Check:
sub replaces first match only [OK]
- Thinking sub replaces all matches
- Confusing sub with gsub
- Expecting all words to change
text <- "hello world example"
new_text <- sub(" ", "_", text)
print(new_text)Solution
Step 1: Identify function behavior
subreplaces only the first match, so only the first space is replaced.Step 2: Suggest correct function for all replacements
To replace all spaces,gsubshould be used instead ofsub.Final Answer:
sub replaces only the first space, use gsub to replace all spaces. -> Option DQuick Check:
Use gsub for all matches, sub for first only [OK]
- Using sub when gsub is needed
- Thinking space pattern is invalid
- Changing replacement character unnecessarily
c("cat123", "dog456", "bird789"). You want to remove all digits from each string. Which R code correctly does this using gsub?Solution
Step 1: Identify pattern to remove digits
The pattern "[0-9]" matches any single digit; "\\d+" matches one or more digits.Step 2: Choose function to replace all digits
Usegsubto replace all digit occurrences, not just the first.Step 3: Check options
gsub("[0-9]", "", c("cat123", "dog456", "bird789")) usesgsubwith "[0-9]" which removes all digits correctly.Final Answer:
gsub("[0-9]", "", c("cat123", "dog456", "bird789")) -> Option AQuick Check:
gsub + digit pattern removes all digits [OK]
- Using sub instead of gsub, removing only first digit
- Incorrect regex pattern for digits
- Confusing escape sequences in regex
Ready to prove it?
Pass the test and this pattern moves unknown
