Hash Maps & Sets · 15 min · free lesson

Challenge: Indexed Randomized Set

Tokens addN and removeN arrive separated by spaces. Adding a value already present and removing an absent value change nothing. Apply them to dense vector storage, then return the remaining values sorted ascending, or an empty string when nothing remains.

Core idea

The last value now occupies the removed slot. Tokens addN and removeN arrive separated by spaces. Adding a value already present and removing an absent value change nothing. Apply them to dense vector storage, then return the remaining values sorted ascending, or an empty string when nothing remains.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Combine a dense vector with a value-to-index map; delete by swapping with the last item.

O(1) expected per operation · O(n) space36 execution steps
main · before line 48Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputadd1 add2 remove2 add3

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 48
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
#[derive(Default)]
struct DenseSet {
    values: Vec<i32>,
    index: std::collections::HashMap<i32, usize>,
}
impl DenseSet {
    fn insert(&mut self, x: i32) {
        if self.index.contains_key(&x) {
            return;
        }
        self.index.insert(x, self.values.len());
        self.values.push(x);
    }
    fn remove(&mut self, x: i32) {
        if let Some(i) = self.index.remove(&x) {
            self.values.swap_remove(i);
            if i < self.values.len() {
                self.index.insert(self.values[i], i);
            }
        }
    }
    // A caller-supplied uniform index gives a uniform stored element.
    fn sample(&self, uniform_index: usize) -> Option<i32> {
        self.values.get(uniform_index).copied()
    }
}
fn dense_operations(ops: &[(bool, i32)]) -> Vec<i32> {
    let mut set = DenseSet::default();
    for &(insert, x) in ops {
        if insert {
            set.insert(x);
        } else {
            set.remove(x);
        }
    }
    let _ = set.sample(0);
    set.values.sort_unstable();
    set.values
}
 
fn main() {
    let result = csv(dense_operations(&[
        (true, 1),
        (true, 2),
        (false, 2),
        (true, 3),
    ]));
    println!("{result}");
}

Try your own version

Change the independent fixture `add1 add2 remove2 add3` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `add4 add9 remove4 add7`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Hash Maps & Sets infographic; panel 4 illustrates Randomized Set.
Randomized Set: follow panel 4 to see the operation, then trace the lesson's own example.

Understand it

The last value now occupies the removed slot. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input add1 add2 remove2 add3, the worked program returns 1,3. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input add4 add9 remove4 add7; predict that result before opening the answer reveal. The precise contract is: Tokens addN and removeN arrive separated by spaces. Adding a value already present and removing an absent value change nothing. Apply them to dense vector storage, then return the remaining values sorted ascending, or an empty string when nothing remains.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Tokens addN and removeN arrive separated by spaces. Adding a value already present and removing an absent value change nothing. Apply them to dense vector storage, then return the remaining values sorted ascending, or an empty string when nothing remains. On input add4 add9 remove4 add7, predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Combine a dense vector with a value-to-index map; delete by swapping with the last item. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A key-derived representation lets later work reuse an earlier fact. It may be a set, a map from keys to state, compressed ranks, or a rolling fingerprint; name which one this pattern uses. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(1) expected per operation · O(n) space; explain which operation dominates it and how many times the input can trigger that operation. Check missing keys, repeated keys, and collisions conceptually; expected constant-time operations are not a worst-case promise. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Combine a dense vector with a value-to-index map; delete by swapping with the last item.

When to use it: O(1) insert, delete, and random access

Complexity: O(1) expected per operation · O(n) space

Input: add4 add9 remove4 add7

Read the code

fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
#[derive(Default)]
struct DenseSet {
    values: Vec<i32>,
    index: std::collections::HashMap<i32, usize>,
}
impl DenseSet {
    fn insert(&mut self, x: i32) {
        if self.index.contains_key(&x) {
            return;
        }
        self.index.insert(x, self.values.len());
        self.values.push(x);
    }
    fn remove(&mut self, x: i32) {
        if let Some(i) = self.index.remove(&x) {
            self.values.swap_remove(i);
            if i < self.values.len() {
                self.index.insert(self.values[i], i);
            }
        }
    }
    // A caller-supplied uniform index gives a uniform stored element.
    fn sample(&self, uniform_index: usize) -> Option<i32> {
        self.values.get(uniform_index).copied()
    }
}
fn dense_operations(ops: &[(bool, i32)]) -> Vec<i32> {
    let mut set = DenseSet::default();
    for &(insert, x) in ops {
        if insert {
            set.insert(x);
        } else {
            set.remove(x);
        }
    }
    let _ = set.sample(0);
    set.values.sort_unstable();
    set.values
}

fn main() {
    let result = csv(dense_operations(&[
        (true, 1),
        (true, 2),
        (false, 2),
        (true, 3),
    ]));
    println!("{result}");
}

Complete std-only randomized-set program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Tokens addN and removeN arrive separated by spaces. Adding a value already present and removing an absent value change nothing. Apply them to dense vector storage, then return the remaining values sorted ascending, or an empty string when nothing remains.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement randomized-set")
}

Try it

Tokens addN and removeN arrive separated by spaces. Adding a value already present and removing an absent value change nothing. Apply them to dense vector storage, then return the remaining values sorted ascending, or an empty string when nothing remains.

What success looks like: The private harness prints PASS randomized-set. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for randomized-set: with input add7 remove7 add8, what result should solve return?

Reveal the answer
  1. 8
  2. 9
  3. 7

For this input the result is 8. The last value now occupies the removed slot. Compare this independent fixture with the worked trace: After adding 4 and 9, removing 4 moves 9 into slot 0. Its map entry must become 9→0. Adding 7 gives dense storage [9,7]; sorting only the final report produces 7,9, without changing the constant-time storage operations.

Go deeper

Common misconception: “The remaining values are automatically reindexed by HashMap”

The last value now occupies the removed slot. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: The last value now occupies the removed slot. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses add1 add2 remove2 add3 and computes 1,3. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For add7 remove7 add8, the independently calculated result is 8. The complexity discussion uses O(1) expected per operation · O(n) space. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture add1 add2 remove2 add3 in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge add4 add9 remove4 add7.

Connections

  • Indexed Randomized Set: When to Use It: O(1) insert, delete, and random access
  • Rolling Fingerprint: Mental Model: Update a window hash by removing the outgoing contribution and adding the incoming one.
Reveal the Algorithm Atlas answer

7,9

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Indexed Randomized Set (courseId "algorithms", lessonId "algorithm.randomized-set.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.randomized-set.challenge
Goal: The last value now occupies the removed slot. Tokens addN and removeN arrive separated by spaces. Adding a value already present and removing an absent value change nothing. Apply them to dense vector storage, then return the remaining values sorted ascending, or an empty string when nothing remains.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.randomized-set.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.