Character type in Rust - Time & Space Complexity
When working with characters in Rust, it's important to understand how operations on them scale as input grows.
We want to know how the time to process characters changes when we handle more of them.
Analyze the time complexity of the following code snippet.
fn count_vowels(text: &str) -> usize {
let mut count = 0;
for ch in text.chars() {
if matches!(ch, 'a' | 'e' | 'i' | 'o' | 'u' |
'A' | 'E' | 'I' | 'O' | 'U') {
count += 1;
}
}
count
}
This function counts how many vowels are in a given text string by checking each character.
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 text.
As the text gets longer, the function 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 work grows directly with the number of characters; double the text, double the checks.
Time Complexity: O(n)
This means the time to count vowels grows in a straight line with the length of the input text.
[X] Wrong: "Checking each character is constant time no matter how long the text is."
[OK] Correct: Actually, the function must look at every character, so more characters mean more work.
Understanding how character processing scales helps you write efficient text handling code, a common task in many programs.
"What if we changed the function to count vowels only in the first half of the text? How would the time complexity change?"
Practice
char variable in Rust?Solution
Step 1: Understand Rust char syntax
Rust uses single quotes forcharliterals, e.g., 'a'. Double quotes are for strings.Step 2: Check each option
let letter: char = 'a'; uses single quotes correctly. let letter: char = "a"; uses double quotes (string). let letter: char = a; misses quotes. let letter: char = `a`; uses backticks, which is invalid.Final Answer:
let letter: char = 'a'; -> Option BQuick Check:
char uses single quotes [OK]
- Using double quotes instead of single quotes
- Omitting quotes around the character
- Using backticks instead of quotes
char variable in Rust?Solution
Step 1: Recall char literal rules
Rustcharliterals must be in single quotes, even for emojis.Step 2: Evaluate options
let smiley: char = '๐'; uses single quotes correctly with the emoji. Double quotes ("๐") create a string. Bare ๐ lacks quotes. Backticks (`๐`) are invalid.Final Answer:
let smiley: char = '๐'; -> Option AQuick Check:
Emoji char uses single quotes [OK]
- Using double quotes for char
- Not quoting the emoji
- Using backticks instead of single quotes
let c: char = 'Z';
println!("{}", c.is_alphabetic());Solution
Step 1: Understand
This method returns true if the char is a letter (A-Z or a-z or other alphabets).is_alphabetic()methodStep 2: Check the character 'Z'
'Z' is an uppercase letter, sois_alphabetic()returns true.Final Answer:
true -> Option AQuick Check:
'Z'.is_alphabetic() = true [OK]
- Confusing output with printing the char itself
- Thinking is_alphabetic() returns the char
- Expecting a compile error
let ch: char = 'ab';
Solution
Step 1: Check char literal rules
Acharcan only hold one Unicode character, so 'ab' is invalid.Step 2: Analyze the error
Using multiple characters inside single quotes causes a compile error.Final Answer:
Multiple characters in single quotes are not allowed -> Option DQuick Check:
char holds one char only [OK]
- Trying to store multiple characters in a char
- Using double quotes for char
- Ignoring compile errors
let s = "Rust ๐ฆ";, which Rust code correctly extracts the crab emoji as a char?Solution
Step 1: Understand string and char indexing in Rust
Rust strings are UTF-8 encoded. The string "Rust ๐ฆ" has 6 chars: 'R'(0),'u'(1),'s'(2),'t'(3),' '(4),'๐ฆ'(5). Crab emoji is the 6th character (index 5), counting chars, not bytes.Step 2: Check each option
let crab = s.chars().nth(5).unwrap(); correctly useschars().nth(5)to get the crab emoji. let crab = s.chars().nth(4).unwrap(); gets the space (index 4). let crab = s[5]; uses byte index (u8, not char). let crab = s[4..5].chars().next().unwrap(); byte slice yields space.Final Answer:
let crab = s.chars().nth(5).unwrap(); -> Option CQuick Check:
Use chars().nth(5) for crab emoji [OK]
- Indexing string bytes directly
- Using wrong index for emoji
- Not unwrapping Option from nth()
Ready to prove it?
Pass the test and this pattern moves unknown
