Collections and Strings
`Vec` and its capacity, `String` vs `&str` and UTF-8, `HashMap` and the entry API, `HashSet`, `BTreeMap` and `VecDeque`.
16 questions
JuniorTheoryCommonHow do [T; N], Vec<T> and &[T] differ, and how do you convert between them?
How do [T; N], Vec<T> and &[T] differ, and how do you convert between them?
An array [T; N] has its length in the type, fixed at compile time, and sits inline, often on the stack. A Vec<T> owns a growable heap buffer. A slice &[T] borrows a run of either, such as &v[1..], and to_vec() copies it into a new Vec.
Common mistakes
- ✗Thinking an array lives on the heap like a
Vec, or that aVeckeeps its elements on the stack - ✗Treating a slice
&[T]as an owned copy rather than a borrowed view of an array or aVec - ✗Writing
fn f(v: &Vec<i32>)where&[i32]would accept arrays, vectors and parts of both
Follow-up questions
- →Why does converting a
Vec<i32>into[i32; 3]withtry_intoreturn aResult? - →What does a
&[T]value itself store, and how large is it on a 64-bit target?
JuniorTheoryCommonWhat does the program print?
What does the program print?
3 1
Open full question →Common mistakes
- ✗Expecting every count to be 1, as if
or_insert(0)reset the value: it inserts 0 only for a missing key and otherwise returns the existing count. - ✗Expecting the first occurrence to be skipped:
or_insertreturns a reference to the fresh 0, and+= 1raises it to 1 at once.
Follow-up questions
- →Why does the counting line need the
*beforecounts.entry(w)? - →How would you write the same count with
or_defaultinstead ofor_insert(0)?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
h, as in Python or JavaScript: a RustStringtakes no numeric index, ands[0]stops the build with E0277. - ✗Expecting the first byte, 104: bytes come from
s.as_bytes()[0]ors.bytes(), never from indexing theStringitself.
Follow-up questions
- →How would you get the first character of
sas anOption<char>? - →Which kind of index does a
Stringaccept, and when does it panic?
JuniorTheoryCommonWhat does the program print?
What does the program print?
12 6
Open full question →Common mistakes
- ✗Expecting
lento count letters: it counts bytes, and each Cyrillic letter is 2 bytes in UTF-8, so «привет» has length 12. - ✗Expecting a string to store each letter as a 4-byte
char: a&strholds UTF-8, where a letter takes 1 to 4 bytes.
Follow-up questions
- →What would the program print for the word
"hello", and why? - →Why does
chars().count()take O(n) time whilelentakes O(1)?
JuniorDebuggingCommonFix code that reads a String after s1 + "-" + &s2 (E0382)
Fix code that reads a String after s1 + "-" + &s2 (E0382)
+ calls add(self, &str): it takes the left String by value, appends the right &str to that same buffer and returns it, so s1 is moved. Build s3 with format!("{s1}-{s2}"), which only borrows, or start from s1.clone().
Common mistakes
- ✗Thinking
+borrows both strings and allocates a new one, as in most languages - ✗Writing
&s1 + "-", which does not compile because&Stringhas no+ - ✗Cloning by reflex where
format!builds the result without moving anything
Follow-up questions
- →Why is the right operand of
+a&strand not aString? - →Why is
s1 + &s2cheaper thanformat!whens1is no longer needed?
JuniorTheoryCommonWhat does the program print?
What does the program print?
Some(2) None
Open full question →Common mistakes
- ✗Expecting a panic, as with
v[10]:getchecks the index itself and returnsNonewhen there is no element. - ✗Expecting
get(1)to return the first element: indices start at 0, soget(1)isSome(2).
Follow-up questions
- →What would
println!("{}", v[10])do in the same program? - →How would you print the element from
v.get(1)without theSomearound it?
JuniorTheoryCommonWhat does the program print?
What does the program print?
1 10
Open full question →Common mistakes
- ✗Expecting
with_capacity(10)to create ten elements: it only reserves room, so after onepushthe length is 1. - ✗Expecting
capacityto followlen: it counts the slots in the buffer, which stay 10 until the vector outgrows them.
Follow-up questions
- →What would
lenandcapacitybe after eleven calls topush? - →What does
v[0]do right afterVec::with_capacity(10), before anypush?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
1becausepushonly adds at the end: it may move every element to a new place, so the compiler refuses a live&v[0]across it (E0502). - ✗Expecting the conflict to show up at run time: borrow rules are checked during the build, so this program never starts.
Follow-up questions
- →How would you change one line so that the program compiles and prints
1? - →Why is a live reference to an element a problem when
pushneeds more room?
MiddleCodeCommonTurn an O(n²) search for a pair with a given sum into one O(n) pass
Turn an O(n²) search for a pair with a given sum into one O(n) pass
Walk once with a HashMap from each seen value to its index. For x at i, look up target - x: a hit j gives (j, i), else insert x. Looking up before inserting stops x pairing with itself; O(n) average time, O(n) extra memory.
Common mistakes
- ✗Inserting
xbefore looking uptarget - x, so a single 3 pairs with itself for target 6 - ✗Using a
HashSet, which tells whether a value was seen but keeps no index - ✗Calling sort plus two pointers O(n): the sort alone is O(n log n) and loses the indices
Follow-up questions
- →What is the worst-case time of this solution, and how does std's default hasher guard it?
- →How would you find the first value that repeats, using only a
HashSet?
MiddleTheoryCommonString vs &str vs str — what is each, and which should a parameter take?
String vs &str vs str — what is each, and which should a parameter take?
String owns a growable UTF-8 heap buffer. str is unsized UTF-8 text, used only behind a pointer; &str is a pointer plus a length. A read-only parameter takes &str, which accepts literals and &String; one that stores text takes String.
Common mistakes
- ✗Calling
stra fixed-length string, although it is unsized and usable only behind a pointer - ✗Taking
&Stringin a parameter, which rejects literals and slices for no gain - ✗Taking
Stringby value in a function that only reads, forcing callers to clone
Follow-up questions
- →How large are
Stringand&stron a 64-bit target, and why do they differ? - →When would a parameter be better declared as
impl Into<String>than as&str?
MiddlePerformanceCommonWhat does push do when a Vec is full, and when should you reserve up front?
What does push do when a Vec is full, and when should you reserve up front?
When len == capacity, push allocates a bigger buffer, moves every element and frees the old one: O(n) once, amortized O(1), as capacity doubles (Vec<i32>: 0, 4, 8, 16). with_capacity/reserve avoid it; shrink_to_fit frees spare room.
Common mistakes
- ✗Calling every
pushO(1), when one that reallocates costs O(n) and only the average is O(1) - ✗Expecting
Vec::with_capacity(10)to hold ten elements, so thatv[0]would not panic - ✗Expecting
clearortruncateto return memory, which takesshrink_to_fitorshrink_to
Follow-up questions
- →Why does doubling give amortized O(1), while a fixed growth step gives O(n²) in total?
- →When is
reserve_exactbetter thanreserve, and why can it hurt inside a loop?
MiddleTheoryCommonWhy does s[0] not compile for a String, and what do you use instead?
Why does s[0] not compile for a String, and what do you use instead?
A String is UTF-8 bytes: a char takes 1–4 bytes, a visible letter may be several chars, so s[0] has no single meaning or O(1) answer and is refused (E0277). Pick the unit: bytes(), chars(), char_indices() or a byte range &s[a..b].
Common mistakes
- ✗Believing
s[0]compiles and returns a byte or achar, as in C or Python - ✗Treating a
charas a visible letter, althoughécan be twochars and an emoji several - ✗Calling
chars().nth(i)in a loop, which rescans the string each time and costs O(n) per lookup
Follow-up questions
- →What happens at run time when
&s[0..1]cuts a Cyrillic letter in half? - →How would you count user-visible letters, given that std has no grapheme API?
MiddleTheoryOccasionalWhich traits must a map key implement, and what if Hash and Eq disagree?
Which traits must a map key implement, and what if Hash and Eq disagree?
A HashMap key needs Eq + Hash, and a == b must imply equal hashes; a BTreeMap key needs Ord. If equal keys hash differently, lookups miss stored entries and duplicates appear: wrong results, but no UB. f64 is neither Eq nor Hash.
Common mistakes
- ✗Reversing the rule: equal keys must hash equally, but equal hashes may belong to different keys
- ✗Implementing
PartialEqby hand while derivingHash, so the two disagree on which fields count - ✗Expecting to insert
f64keys into aHashMap, althoughf64is neitherEqnorHashbecause ofNaN
Follow-up questions
- →Why does changing a key through interior mutability while it sits in a map break lookups?
- →How would you use floating-point values as map keys, given that
f64is notEq?
MiddleCodeOccasionalGroup words by first letter into a HashMap<char, Vec<String>> with entry
Group words by first letter into a HashMap<char, Vec<String>> with entry
Per word take w.chars().next(), skipping the None of an empty word, and call map.entry(c).or_default().push(w.to_string()). entry finds or creates the slot in one lookup; or_default inserts an empty Vec, like or_insert_with(Vec::new).
Common mistakes
- ✗Writing
contains_key, theninsert, thenget_mut: three lookups whereentryneeds one - ✗Taking the key as
w.as_bytes()[0] as char, which garbles any non-ASCII first letter - ✗Believing
or_insert(Vec::new())is lazy, though its argument is always evaluated
Follow-up questions
- →Why does
entrytake the key by value, and what does that cost withStringkeys? - →How would you return the groups sorted by letter, and which map gives that for free?
MiddleCodeOccasionalReverse a string correctly for non-ASCII input such as Cyrillic text
Reverse a string correctly for non-ASCII input such as Cyrillic text
s.chars().rev().collect() decodes UTF-8 and reverses in O(n). Reversing bytes would turn each multibyte letter into invalid UTF-8, which a String may never hold. chars() still splits grapheme clusters such as e plus an accent.
Common mistakes
- ✗Reversing
as_bytes()and callingString::from_utf8(…).unwrap(), which panics on any multibyte letter - ✗Indexing
s[i]in a loop, which does not compile for strings - ✗Assuming
chars().rev()keeps accents and emoji intact, although it splits grapheme clusters
Follow-up questions
- →How would you reverse by grapheme clusters, and why does std not offer it?
- →What does
String::from_utf8check, and why does it return aResult?
MiddleTheoryOccasionalWhen do you pick VecDeque, HashSet, BTreeMap or BinaryHeap over a Vec?
When do you pick VecDeque, HashSet, BTreeMap or BinaryHeap over a Vec?
Vec is the default. VecDeque is a ring buffer with O(1) push and pop at both ends, for queues. HashMap/HashSet find keys in O(1) on average, unordered. BTreeMap/BTreeSet keep keys sorted, O(log n). BinaryHeap pops the max in O(log n).
Common mistakes
- ✗Building a queue on
Vec::remove(0), which shifts every element and costs O(n) - ✗Expecting
HashMaporHashSetto iterate in insertion or sorted order - ✗Assuming
BinaryHeapis sorted or yields the smallest first without wrapping items inReverse
Follow-up questions
- →Why can a
Vecwith a linear search beat aHashMapfor a few dozen elements? - →How do you turn
BinaryHeapinto a min-heap, and what doespeekcost?