String to Integer atoi in DSA Rust - Time & Space Complexity
We want to understand how the time needed to convert a string to an integer changes as the string gets longer.
How does the work grow when the input string size increases?
Analyze the time complexity of the following code snippet.
fn my_atoi(s: &str) -> i32 {
let mut result = 0i32;
let mut sign = 1;
let mut chars = s.trim_start().chars().peekable();
if let Some(&c) = chars.peek() {
if c == '-' {
sign = -1;
chars.next();
} else if c == '+' {
chars.next();
}
}
for c in chars {
if let Some(d) = c.to_digit(10) {
result = result.saturating_mul(10).saturating_add(d as i32);
} else {
break;
}
}
result * sign
}
This code converts a string to an integer by reading characters one by one, handling optional sign, and stopping at the first non-digit.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the trimmed string after optional sign.
- How many times: Up to once for each character until a non-digit is found or string ends.
As the input string gets longer, the code checks each character once until it stops.
| 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 processed.
Time Complexity: O(n)
This means the time to convert grows linearly with the length of the input string.
[X] Wrong: "The function runs in constant time because it just converts a string to a number."
[OK] Correct: The function must check each character until it finds a non-digit, so the time depends on string length.
Understanding this helps you explain how simple string parsing scales and shows you can analyze loops over input data clearly.
"What if the input string is very long but contains a non-digit character near the start? How would the time complexity change?"
Practice
atoi function do when given a string input?Solution
Step 1: Understand the purpose of atoi
The atoi function stands for ASCII to integer, which means it converts a string that looks like a number into an actual integer value.Step 2: Differentiate from other string operations
It does not convert integers to strings, sort characters, or just check digits; it specifically parses the string to produce an integer.Final Answer:
Converts a string representing a number into an integer -> Option DQuick Check:
atoi = string to integer conversion [OK]
- Thinking atoi converts integer to string
- Assuming atoi sorts characters
- Believing atoi only checks digits without conversion
"1234" to an integer using atoi logic?Solution
Step 1: Identify Rust's way to convert string to integer
Rust uses theparse()method on strings to convert them to numbers, andunwrap()extracts the value or panics on error.Step 2: Check other options for correctness
let num = atoi("1234"); uses a non-existentatoifunction in Rust. Options A and D convert to strings, not integers.Final Answer:
let num = "1234".parse::<i32>().unwrap(); -> Option AQuick Check:
Rust string to int uses parse() [OK]
- Using a non-existent atoi function in Rust
- Confusing string to integer with string to string conversion
- Missing unwrap() causing compile errors
let s = " -42abc";
let num = s.trim().chars().take_while(|c| c.is_digit(10) || *c == '-').collect::<String>().parse::<i32>().unwrap_or(0);
println!("{}", num);Solution
Step 1: Analyze string trimming and character filtering
The string is trimmed to "-42abc". The code takes characters while they are digits or '-'. It stops at 'a' which is not digit or '-'. So it collects "-42".Step 2: Parse the collected string to integer
Parsing "-42" to i32 works, so num should be -42. But the code uses unwrap_or(0), which only returns 0 if parse fails. Here parse succeeds, so num = -42.Step 3: Check the actual code behavior
However, the code uses take_while with condition c.is_digit(10) || *c == '-'. The '-' is allowed anywhere, so it collects "-42" correctly. So num = -42.Final Answer:
0 -> Option AQuick Check:
Parsed number = 0 because string "-42" is invalid for parse::<i32>() due to '-' in middle [OK]
- Assuming parsing fails due to trailing letters
- Ignoring that '-' is allowed in take_while
- Expecting runtime error due to unwrap_or
fn string_to_int(s: &str) -> i32 {
let mut result = 0;
for c in s.chars() {
if c >= '0' && c <= '9' {
result = result * 10 + (c as i32);
} else {
break;
}
}
result
}Solution
Step 1: Understand char to i32 casting
Casting a char like '3' to i32 gives its ASCII code (51), not the digit 3.Step 2: Identify correct digit extraction
To get digit value, subtract '0' as in (c as i32 - '0' as i32). Without this, result accumulates wrong values.Final Answer:
Casting char to i32 adds ASCII value, not digit value -> Option BQuick Check:
Char to digit needs subtraction of '0' [OK]
- Using char as i32 directly without subtracting '0'
- Not breaking loop on non-digit characters
- Ignoring negative number handling
atoi function in Rust that handles optional leading spaces, optional '+' or '-' sign, and stops parsing at the first non-digit character. Which approach below correctly handles all these cases?Solution
Step 1: Handle leading spaces and sign
Trimming spaces and checking for '+' or '-' sign is necessary to correctly interpret the number's sign.Step 2: Iterate characters and convert digits
Iterate over characters, convert digits to integer values, and stop parsing when a non-digit is found to avoid errors.Step 3: Apply sign and return result
After parsing digits, apply the detected sign to the result before returning.Final Answer:
Trim spaces, check sign, iterate chars converting digits, stop on non-digit, apply sign -> Option CQuick Check:
Proper atoi handles spaces, sign, digits, and stops correctly [OK]
- Parsing entire string without trimming or sign handling
- Summing byte values instead of digit conversion
- Ignoring sign or non-digit stopping conditions
Ready to prove it?
Pass the test and this pattern moves unknown
