Problem
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 arraymatrix
, where all elements are initially set to 0.void setCell(int x, int y, int z)
Sets the value atmatrix[x][y][z]
to 1.void unsetCell(int x, int y, int z)
Sets the value atmatrix[x][y][z]
to 0.int largestMatrix()
Returns the indexx
wherematrix[x]
contains the most number of 1’s. If there are multiple such indices, return the largestx
.
Examples
Example 1:
|
|
Solution
Method 1 – Hash Set and 3D Array for Efficient Layer Tracking
Intuition
To efficiently support set, unset, and query operations in a 3D binary matrix, we can use a 3D array for the matrix and maintain a set for each layer to track which cells are set. This allows for fast updates and queries for each layer.
Approach
- Use a 3D array (or a dictionary of sets) to represent the matrix.
- For each layer, maintain a set of (row, col) pairs that are set to 1.
set(x, y, z)
: Set the cell (x, y, z) to 1 and add (x, y) to the set for layer z.unset(x, y, z)
: Set the cell (x, y, z) to 0 and remove (x, y) from the set for layer z.isSet(x, y, z)
: Return True if (x, y) is in the set for layer z.getLayer(z)
: Return a list of all (x, y) pairs set in layer z.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
for set, unset, isSet;O(k)
for getLayer, where k is the number of set cells in the layer. - 🧺 Space complexity:
O(n * m * l)
in the worst case, if all cells are set.