Diagonal Difference

Sort by

recency

|

5842 Discussions

|

  • + 0 comments

    Airdrops can be a bit confusing, but Paybis does a great job of breaking it down. They explain how airdrops are used by projects to distribute tokens to users, often to promote a new project or reward loyal users. It's a good read if you're curious about how airdrops work and how to participate safely. Check it out here

  • + 0 comments

    Locksmith Gool services provide quick, reliable solutions for urgent lockouts, broken keys, and security issues, ensuring your property is always protected. Just like solving Diagonal Difference in mathematics requires precision and accuracy, professional locksmiths apply expertise to deliver effective results. From residential to commercial needs, they respond promptly with trusted skills, offering peace of mind and dependable security whenever you face unexpected challenges that demand immediate attention and professional assistance.

  • + 0 comments

    O(n) solution:

    def diagonalDifference(arr):
    ROWS = len(arr)
    res = 0
    for i in range(ROWS):
    diff = (arr[i][i] - arr[i][ROWS-1-i])
    res += diffreturn abs(res)
    
  • + 0 comments
    def diagonalDifference(arr):
        # Write your code here
        s = 0
        size = len(arr)
        for i in range(size):
            line = arr[i]
            diff = line[i] - line[size - 1 - i]
            s += diff
        return abs(s)
    
  • + 0 comments

    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.

    def diagonalDifference(arr):
        n = len(arr)
        left_diag = 0
        right_diag = 0
        for i in range(n):
            for j in range(n):
                if i == j:
                    left_diag += arr[i][j]
                if i + j == n-1:
                    right_diag += arr[i][j]
        return abs(left_diag - right_diag)
    

    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.

    def diagonalDifference(arr):
        n = len(arr)
        left_diag = 0
        right_diag = 0
        for i in range(n):
            left_diag += arr[i][i]
            right_diag += arr[i][n-i-1]
        return abs(left_diag - right_diag)
    

    Time Complexity: O(n), just one pass Space Complexity: O(1) >

    .