526. Design a 3D Binary Matrix with Efficient Layer Tracking

Given an n x n x n binary 3D matrix.

Implement the Matrix3D class:

  • Matrix3D(int n): Initializes the object with an n x n x n binary matrix, where all elements are initially set to 0.
  • void activateCell(int x, int y, int z): Sets matrix[x][y][z] to 1.
  • void deactivateCell(int x, int y, int z): Sets matrix[x][y][z] to 0.
  • int mostActiveLayer(): Returns the index x where matrix[x] contains the highest number of 1s. If multiple layers have the same maximum count, return the largest x.

Example 1:

Input:

["Matrix3D", "activateCell", "mostActiveLayer", "activateCell", "mostActiveLayer", "activateCell", "mostActiveLayer"]

[[3], [0, 0, 0], [], [1, 1, 2], [], [0, 0, 1], []]

Output: 

[null, null, 0, null, 1, null, 0]

Explanation:

Matrix3D matrix3D = new Matrix3D(3); // Creates a 3x3x3 matrix with all 0s.

matrix3D.activateCell(0, 0, 0); // Sets matrix[0][0][0] to 1.

matrix3D.mostActiveLayer(); // Returns 0 (layer 0 has the most 1s).

matrix3D.activateCell(1, 1, 2); // Sets matrix[1][1][2] to 1.

matrix3D.mostActiveLayer(); // Returns 1 (layers 0 and 1 have the same count, but 1 is the largest).

matrix3D.activateCell(0, 0, 1); // Sets matrix[0][0][1] to 1.

matrix3D.mostActiveLayer(); // Returns 0 (layer 0 has the most 1s).

Example 2:

Input:

["Matrix3D", "activateCell", "activateCell", "activateCell", "mostActiveLayer", "deactivateCell", "mostActiveLayer"]

[[3], [0, 1, 2], [2, 2, 2], [2, 0, 1], [], [2, 0, 1], []]

Output:

[null, null, null, null, 2, null, 2]

Explanation:

Matrix3D matrix3D = new Matrix3D(3); // Creates a 3x3x3 matrix with all 0s.

matrix3D.activateCell(0, 1, 2); // Sets matrix[0][1][2] to 1.

matrix3D.activateCell(2, 2, 2); // Sets matrix[2][2][2] to 1.

matrix3D.activateCell(2, 0, 1); // Sets matrix[2][0][1] to 1.

matrix3D.mostActiveLayer(); // Returns 2 (layer 2 has the most 1s).

matrix3D.deactivateCell(2, 0, 1); // Sets matrix[2][0][1] to 0.

matrix3D.mostActiveLayer(); // Returns 2 (layer 2 still has the most 1s).

Now Your Turn!

Pick the correct output for the given input

Input:

["Matrix3D", "activateCell", "mostActiveLayer", "activateCell", "mostActiveLayer", "deactivateCell", "mostActiveLayer"]

[[5], [4, 1, 1], [], [2, 2, 2], [], [4, 1, 1], []]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 100
  • 0 <= x, y, z < n
  • At most 105 calls to activateCell and deactivateCell.
  • At most 104 calls to mostActiveLayer.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Matrix3D {
public:
Matrix3D(int n) : n(n) {
}
void activateCell(int x, int y, int z) {
}
void deactivateCell(int x, int y, int z) {
}
int mostActiveLayer() {
}
};
 
Test Case

Input:

Input
Operations