Advertisement
satishfrontenddev5

Untitled

Feb 18th, 2024
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. You are given an integer n and a 0-indexed 2D array queries where queries[i] = [typei, indexi, vali].
  2.  
  3. 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:
  4.  
  5. if typei == 0, set the values in the row with indexi to vali, overwriting any previous values.
  6. if typei == 1, set the values in the column with indexi to vali, overwriting any previous values.
  7. Return the sum of integers in the matrix after all queries are applied.
  8.  
  9. ----------  Solutions-------------
  10. To solve this problem, you can follow these steps:
  11.  
  12. 1. Initialize a 2D array `matrix` of size `n x n` filled with zeros.
  13. 2. Iterate through each query in the `queries` array.
  14. 3. For each query:
  15.   - Check if `typei` is 0 or 1.
  16.   - If `typei` is 0, update the row with index `indexi` to have all values as `vali`.
  17.   - If `typei` is 1, update the column with index `indexi` to have all values as `vali`.
  18. 4. After applying all queries, calculate the sum of integers in the matrix.
  19. 5. Return the sum.
  20.  
  21. Here's a JavaScript function implementing the above steps:
  22.  
  23. ```javascript
  24. function sumAfterQueries(n, queries) {
  25.     let matrix = Array.from({ length: n }, () => Array(n).fill(0)); // Step 1
  26.  
  27.     for (let [type, index, val] of queries) { // Step 2
  28.         if (type === 0) { // Step 3
  29.             matrix[index].fill(val);
  30.         } else if (type === 1) {
  31.             for (let i = 0; i < n; i++) {
  32.                 matrix[i][index] = val;
  33.             }
  34.         }
  35.     }
  36.  
  37.     let sum = 0;
  38.     for (let row of matrix) { // Step 4
  39.         sum += row.reduce((acc, curr) => acc + curr, 0);
  40.     }
  41.  
  42.     return sum; // Step 5
  43. }
  44. ```
  45.  
  46. 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