We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Warmup
- Diagonal Difference
- Discussions
Diagonal Difference
Diagonal Difference
Sort by
recency
|
5838 Discussions
|
Please Login in order to post a comment
Python Brute Force Solution
For the left-to-right diagonal: Loop through all elements, sum elements where row index == column index.
For the right-to-left diagonal: Loop through all elements, sum elements where row index + column index == n-1.
Time Complexity: O(n²), two nested loops. Space Complexity: O(1)
Optimal Solution You don't need to traverse every element, each diagonal has only n elements (one per row/column).
Access the diagonals directly using index formulas in a single loop.
Time Complexity: O(n), just one pass Space Complexity: O(1) >
.
public static int diagonalDifference(List> arr) { // Write your code here int sum=0; for(int i=0; i
public static int diagonalDifference(List> arr) { int n = arr.size(); /// tam de la matriz int diagnonalPrincipal = 0; int diagonalSecundaria = 0;
This is my code using C: int diagonalDifference(int arr_rows, int arr_columns, int** arr) { int x = 0; int y = 0; for (int i = 0; i < arr_rows; i ++) { x += arr[i][i]; y += arr[arr_rows - i - 1][i]; }
return abs(x-y); }
Can some one explain why it is not possible to let int N = arr_rows?
O(n) typescript solution