Challenge - 5 Problems
String Reversal Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of reversing a string using chars().rev().collect()
What is the output of this Rust code snippet that reverses a string?
DSA Rust
fn main() {
let original = "hello";
let reversed: String = original.chars().rev().collect();
println!("{}", reversed);
}Attempts:
2 left
💡 Hint
chars() returns characters, rev() reverses iterator, collect() gathers into String.
✗ Incorrect
The code reverses the characters of the string "hello" and prints it. The output is "olleh" without extra newline characters in the string itself.
❓ Predict Output
intermediateOutput of reversing a string using bytes().rev().collect()
What happens when reversing a string using bytes().rev().collect() in Rust?
DSA Rust
fn main() {
let original = "hello";
let reversed: Vec<u8> = original.bytes().rev().collect();
let reversed_str = String::from_utf8(reversed).unwrap();
println!("{}", reversed_str);
}Attempts:
2 left
💡 Hint
bytes() returns bytes, rev() reverses bytes, from_utf8 converts bytes back to string.
✗ Incorrect
Since "hello" is ASCII, reversing bytes is same as reversing characters. The output is "olleh".
❓ Predict Output
advancedOutput of reversing a Unicode string with chars().rev().collect()
What is the output of reversing the Unicode string "héllo" using chars().rev().collect() in Rust?
DSA Rust
fn main() {
let original = "héllo";
let reversed: String = original.chars().rev().collect();
println!("{}", reversed);
}Attempts:
2 left
💡 Hint
chars() handles Unicode characters correctly.
✗ Incorrect
The code reverses the Unicode string correctly by characters, so the accented 'é' stays intact and reversed properly.
❓ Predict Output
advancedWhat error occurs when reversing a string using bytes().rev().collect() on Unicode?
What happens when reversing the Unicode string "héllo" using bytes().rev().collect() and converting to String in Rust?
DSA Rust
fn main() {
let original = "héllo";
let reversed: Vec<u8> = original.bytes().rev().collect();
let reversed_str = String::from_utf8(reversed).unwrap();
println!("{}", reversed_str);
}Attempts:
2 left
💡 Hint
Reversing bytes of multi-byte Unicode characters breaks UTF-8 encoding.
✗ Incorrect
Reversing bytes of Unicode string breaks multi-byte characters, causing invalid UTF-8 and panic on from_utf8().
🧠 Conceptual
expertWhy is chars().rev().collect() preferred over bytes().rev().collect() for string reversal in Rust?
Choose the best reason why reversing a string with chars().rev().collect() is safer than using bytes().rev().collect() in Rust.
Attempts:
2 left
💡 Hint
Think about how Unicode characters are stored and how reversing bytes affects them.
✗ Incorrect
chars() iterates over Unicode scalar values, so reversing preserves character integrity. bytes() reverses raw bytes, which can break multi-byte characters and cause invalid UTF-8.
