#3391
Medium Algorithms Design a 3d binary matrix with efficient layer tracking
Array Hash Table Design Heap (Priority Queue) Matrix Ordered Set
67.2% acceptance
Mar 31, 2026
9
1
You are given a n x n x n binary 3D array matrix.
Implement the Matrix3D class:
Matrix3D(int n) Initializes the object with the 3D binary array matrix, where all elements are initially set to 0.
void setCell(int x, int y, int z) Sets the value at matrix[x][y][z] to 1.
void unsetCell(int x, int y, int z) Sets the value at matrix[x][y][z] to 0.
int largestMatrix() Returns the index x where matrix[x] contains the most number of 1's. If there are multiple such indices, return the largest x.
Solution
Rust
Time O(n * m)
Space O(n * m)
use std::collections::BTreeSet;
struct Matrix3D {
n: usize,
cells: Vec<Vec<Vec<bool>>>,
count: Vec<i32>,
set: BTreeSet<(i32, i32)>, // (-count, -x) so first = max count, largest x
}
impl Matrix3D {
fn new(n: i32) -> Self {
let n = n as usize;
let mut set = BTreeSet::new();
for x in 0..n {
set.insert((0, -(x as i32)));
}
Matrix3D {
n,
cells: vec![vec![vec![false; n]; n]; n],
count: vec![0; n],
set,
}
}
fn set_cell(&mut self, x: i32, y: i32, z: i32) {
let (xu, yu, zu) = (x as usize, y as usize, z as usize);
if !self.cells[xu][yu][zu] {
self.cells[xu][yu][zu] = true;
self.set.remove(&(-self.count[xu], -x));
self.count[xu] += 1;
self.set.insert((-self.count[xu], -x));
}
}
fn unset_cell(&mut self, x: i32, y: i32, z: i32) {
let (xu, yu, zu) = (x as usize, y as usize, z as usize);
if self.cells[xu][yu][zu] {
self.cells[xu][yu][zu] = false;
self.set.remove(&(-self.count[xu], -x));
self.count[xu] -= 1;
self.set.insert((-self.count[xu], -x));
}
}
fn largest_matrix(&self) -> i32 {
let &(_, neg_x) = self.set.iter().next().unwrap();
-neg_x
}
}
/*
* Your Matrix3D object will be instantiated and called as such:
* let obj = Matrix3D::new(n);
* obj.set_cell(x, y, z);
* obj.unset_cell(x, y, z);
* let ret_3: i32 = obj.largest_matrix();
*/