Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- You are given an integer n and a 0-indexed 2D array queries where queries[i] = [typei, indexi, vali].
- Initially, there is a 0-indexed n x n matrix filled with 0's. For each query, you must apply one of the following changes:
- if typei == 0, set the values in the row with indexi to vali, overwriting any previous values.
- if typei == 1, set the values in the column with indexi to vali, overwriting any previous values.
- Return the sum of integers in the matrix after all queries are applied.
- ---------- Solutions-------------
- To solve this problem, you can follow these steps:
- 1. Initialize a 2D array `matrix` of size `n x n` filled with zeros.
- 2. Iterate through each query in the `queries` array.
- 3. For each query:
- - Check if `typei` is 0 or 1.
- - If `typei` is 0, update the row with index `indexi` to have all values as `vali`.
- - If `typei` is 1, update the column with index `indexi` to have all values as `vali`.
- 4. After applying all queries, calculate the sum of integers in the matrix.
- 5. Return the sum.
- Here's a JavaScript function implementing the above steps:
- ```javascript
- function sumAfterQueries(n, queries) {
- let matrix = Array.from({ length: n }, () => Array(n).fill(0)); // Step 1
- for (let [type, index, val] of queries) { // Step 2
- if (type === 0) { // Step 3
- matrix[index].fill(val);
- } else if (type === 1) {
- for (let i = 0; i < n; i++) {
- matrix[i][index] = val;
- }
- }
- }
- let sum = 0;
- for (let row of matrix) { // Step 4
- sum += row.reduce((acc, curr) => acc + curr, 0);
- }
- return sum; // Step 5
- }
- ```
- You can then call this function with the given `n` and `queries` array to get the sum of integers in the matrix after all queries are applied.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement