LeetCode 2718: Sum of Matrix After Queries Solution
Master LeetCode problem 2718 (Sum of Matrix After Queries), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2718. Sum of Matrix After Queries
Problem Explanation
Explanation:
To solve this problem, we can iterate through each query and update the matrix based on the type of query (row or column update). We can keep track of the sum of the matrix elements after each update and return it at the end.
Here are the steps:
- Initialize a 2D matrix of size
n x nfilled with zeros. - Iterate through each query:
- For type 0 query, update the row with the given index to the specified value.
- For type 1 query, update the column with the given index to the specified value.
- Update the sum of the matrix elements after each query.
- Return the final sum of the matrix.
Time complexity: O(n + queries.length)
Space complexity: O(n^2)
:
Solution Code
class Solution {
public int sumMatrixAfterQueries(int n, int[][] queries) {
int[][] matrix = new int[n][n];
int sum = 0;
for (int[] query : queries) {
int type = query[0];
int index = query[1];
int val = query[2];
if (type == 0) {
for (int j = 0; j < n; j++) {
matrix[index][j] = val;
sum += val - matrix[index][j];
}
} else {
for (int i = 0; i < n; i++) {
matrix[i][index] = val;
sum += val - matrix[i][index];
}
}
}
return sum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2718 (Sum of Matrix After Queries)?
This page provides optimized solutions for LeetCode problem 2718 (Sum of Matrix After Queries) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2718 (Sum of Matrix After Queries)?
The time complexity for LeetCode 2718 (Sum of Matrix After Queries) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2718 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2718 in Java, C++, or Python.