Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a key-value pair into a binary search tree (BST).
DSA Rust
fn insert(root: &mut Option<Box<Node>>, key: i32, value: i32) {
match root {
None => *root = Some(Box::new(Node { key, value, left: None, right: None })),
Some(ref mut node) => {
if key < node.key {
insert(&mut node.left, key, value);
} else if key > node.key {
insert(&mut node.right, key, value);
} else {
node.value = [1];
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the key instead of the value.
Trying to assign to root instead of node.value.
✗ Incorrect
When the key already exists in the BST, we update the node's value with the new value provided.
2fill in blank
mediumComplete the code to check if a key exists in a hash map.
DSA Rust
fn contains_key(map: &std::collections::HashMap<i32, i32>, key: i32) -> bool {
map.[1](&key)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using get which returns an Option instead of a boolean.
Using insert or remove which modify the map.
✗ Incorrect
The method contains_key checks if the hash map has the given key.
3fill in blank
hardFix the error in the code to find the minimum key in a BST.
DSA Rust
fn find_min(root: &Option<Box<Node>>) -> Option<i32> {
match root {
None => None,
Some(node) => {
if node.left.is_none() {
Some(node.[1])
} else {
find_min(&node.left)
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning node.value instead of node.key.
Trying to access node.left or node.right instead of node.key.
✗ Incorrect
The minimum key in a BST is found by going left until no left child exists, then returning the node's key.
4fill in blank
hardFill both blanks to create a hash map from a vector of key-value pairs and check if a key exists.
DSA Rust
let pairs = vec![(1, 10), (2, 20), (3, 30)]; let map: std::collections::HashMap<_, _> = pairs.[1]().collect(); let exists = map.[2](&2);
Attempts:
3 left
💡 Hint
Common Mistakes
Using iter instead of into_iter which borrows instead of consuming.
Using get which returns Option instead of boolean.
✗ Incorrect
We convert the vector into an iterator with into_iter and then collect into a hash map. To check if key 2 exists, we use contains_key.
5fill in blank
hardFill all three blanks to create a BST from a vector, insert a new key-value pair, and find the minimum key.
DSA Rust
let mut root: Option<Box<Node>> = None; for (k, v) in vec![(5, 50), (3, 30), (7, 70)] { insert(&mut root, k, v); } insert(&mut root, [1], [2]); let min_key = find_min(&[3]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using None instead of root for find_min.
Inserting a key already in the BST.
✗ Incorrect
We insert key 2 with value 20 into the BST rooted at root, then find the minimum key starting from root.
