String Basics and Memory Representation in DSA Rust - Time & Space Complexity
We want to understand how the time to work with strings grows as the string gets longer.
How does the length of a string affect operations like copying or reading it?
Analyze the time complexity of the following code snippet.
fn copy_string(s: &String) -> String {
let mut new_string = String::new();
for ch in s.chars() {
new_string.push(ch);
}
new_string
}
This code copies a string by reading each character and adding it to a new string.
- Primary operation: Looping through each character of the input string.
- How many times: Exactly once for each character in the string (length n).
As the string gets longer, the number of steps grows directly with its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character copies |
| 100 | About 100 character copies |
| 1000 | About 1000 character copies |
Pattern observation: The work grows evenly as the string length grows.
Time Complexity: O(n)
This means the time to copy the string grows in direct proportion to its length.
[X] Wrong: "Copying a string is instant and does not depend on its size."
[OK] Correct: Each character must be read and written, so longer strings take more time.
Understanding how string operations scale helps you write efficient code and explain your choices clearly.
"What if we used a string slice (&str) instead of a String for copying? How would the time complexity change?"
Practice
String type in Rust represent?Solution
Step 1: Understand Rust string types
Rust has two main string types:Stringand string slices (&str).Stringis growable and stored on the heap.Step 2: Compare options with definitions
A growable, heap-allocated string correctly describesStringas growable and heap-allocated. Others describe slices or fixed arrays.Final Answer:
A growable, heap-allocated string -> Option AQuick Check:
String = growable heap string [OK]
- Confusing String with &str (string slice)
- Thinking String is fixed size
- Assuming String is immutable
String in Rust?Solution
Step 1: Recall Rust String creation syntax
In Rust,String::new()creates a new empty String.Step 2: Check each option syntax
let s = String::new(); uses correct Rust syntax. The other options use invalid Rust syntax for creating a String.Final Answer:
let s = String::new(); -> Option AQuick Check:
String::new() creates empty String [OK]
- Using parentheses like a function call without ::new()
- Trying to use new keyword like other languages
- Using array brackets for String
let s = String::from("hello");
let slice = &s[0..2];
println!("{}", slice);Solution
Step 1: Understand string slicing in Rust
The slice&s[0..2]takes characters from index 0 up to but not including 2.Step 2: Extract substring from "hello"
Characters at index 0 and 1 are 'h' and 'e', so the slice is "he".Final Answer:
he -> Option DQuick Check:
Slice 0..2 of "hello" = "he" [OK]
- Assuming slice includes index 2
- Expecting full string output
- Thinking slicing causes runtime error
let s = String::from("hello");
let slice = &s[0..4];
println!("{}", slice);
let ch = &s[4];Solution
Step 1: Check indexing rules for String
Rust does not allow indexing a String with a single usize likes[4]because strings are UTF-8 encoded and indexing by byte is unsafe.Step 2: Verify other parts
Slice&s[0..4]is valid. Semicolons and String::from usage are correct.Final Answer:
Cannot index String with single usize -> Option BQuick Check:
Single index on String causes error [OK]
- Trying to access String by single index
- Confusing slice range validity
- Ignoring Rust UTF-8 string rules
String containing emoji and letters, which method safely returns the number of characters (not bytes)?Solution
Step 1: Understand difference between bytes and characters
UTF-8 strings store characters as 1 or more bytes.len()returns byte count, not character count.Step 2: Identify method counting characters
s.chars().count()iterates over Unicode scalar values (characters) and counts them correctly.Final Answer:
s.chars().count() -> Option CQuick Check:
chars().count() counts characters, not bytes [OK]
- Using len() which counts bytes, not characters
- Confusing bytes() with chars()
- Assuming as_bytes().len() counts characters
Ready to prove it?
Pass the test and this pattern moves unknown
