Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Diagonal Elements

Problem Statement

Write a Java program that implements a method to extract the main diagonal elements of a square 2D array (matrix) into a 1D array. The main diagonal consists of elements where the row index equals the column index (i.e., matrix[i][i]). The program should return a 1D array containing these elements and test the implementation with various square matrices, including edge cases like 1×1 matrices and matrices with negative numbers. You can visualize this as collecting the numbers along the top-left to bottom-right diagonal of a square grid, like picking out the main diagonal pieces on a chessboard.

Input: A square 2D array (matrix) of integers with dimensions n × n (e.g., matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]). Output: A 1D array containing the main diagonal elements (e.g., [1, 5, 9]). Constraints:

  • 1 ≤ n ≤ 100 (where n is the number of rows and columns).
  • Elements are integers between -10^9 and 10^9.
  • The matrix is guaranteed to be square (number of rows equals number of columns) and non-empty. Example:
  • Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • Output: [1, 5, 9]
  • Explanation: The main diagonal elements are matrix[0][0] = 1, matrix[1][1] = 5, matrix[2][2] = 9.
  • Input: matrix = [[5]]
  • Output: [5]
  • Explanation: The 1×1 matrix has a single diagonal element, 5.

Pseudocode

FUNCTION getMainDiagonal(matrix)
    IF matrix is null OR matrix is empty OR matrix[0] is empty OR rows not equal to columns THEN
        RETURN null
    ENDIF
    SET n to number of rows in matrix
    CREATE result array of size n
    FOR i from 0 to n - 1
        SET result[i] to matrix[i][i]
    ENDFOR
    RETURN result
ENDFUNCTION

FUNCTION main()
    SET testMatrices to square 2D arrays
    FOR each matrix in testMatrices
        CALL getMainDiagonal(matrix)
        PRINT result
    ENDFOR
ENDFUNCTION

Algorithm Steps

  1. Check if the input matrix is null, empty, or not square (rows ≠ columns). If so, return null.
  2. Get the size of the matrix: n (number of rows, equal to columns since square).
  3. Create a 1D result array of size n.
  4. Iterate through indices i from 0 to n-1: a. Set result[i] to matrix[i][i] (the main diagonal element).
  5. Return the result array.
  6. In the main method, create test square matrices of different sizes and call getMainDiagonal to verify correctness.

Java Implementation

public class DiagonalElements {
    // Extracts main diagonal elements into a 1D array
    public int[] getMainDiagonal(int[][] matrix) {
        // Check for null, empty, or non-square matrix
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0 || matrix.length != matrix[0].length) {
            return null;
        }
        // Get matrix size
        int n = matrix.length;
        // Create result array
        int[] result = new int[n];
        // Extract diagonal elements
        for (int i = 0; i < n; i++) {
            result[i] = matrix[i][i];
        }
        return result;
    }

    // Main method to test getMainDiagonal with various inputs
    public static void main(String[] args) {
        DiagonalElements diagonal = new DiagonalElements();

        // Test case 1: 3x3 matrix
        int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println("Test case 1:");
        System.out.println("Matrix:");
        printMatrix(matrix1);
        System.out.print("Main diagonal: ");
        printArray(diagonal.getMainDiagonal(matrix1));

        // Test case 2: 1x1 matrix
        int[][] matrix2 = {{5}};
        System.out.println("Test case 2:");
        System.out.println("Matrix:");
        printMatrix(matrix2);
        System.out.print("Main diagonal: ");
        printArray(diagonal.getMainDiagonal(matrix2));

        // Test case 3: 2x2 matrix with negative numbers
        int[][] matrix3 = {{-1, -2}, {-3, -4}};
        System.out.println("Test case 3:");
        System.out.println("Matrix:");
        printMatrix(matrix3);
        System.out.print("Main diagonal: ");
        printArray(diagonal.getMainDiagonal(matrix3));

        // Test case 4: 4x4 matrix
        int[][] matrix4 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
        System.out.println("Test case 4:");
        System.out.println("Matrix:");
        printMatrix(matrix4);
        System.out.print("Main diagonal: ");
        printArray(diagonal.getMainDiagonal(matrix4));

        // Test case 5: Null matrix
        int[][] matrix5 = null;
        System.out.println("Test case 5:");
        System.out.println("Matrix:");
        printMatrix(matrix5);
        System.out.print("Main diagonal: ");
        printArray(diagonal.getMainDiagonal(matrix5));
    }

    // Helper method to print matrix
    private static void printMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            System.out.println("null");
            return;
        }
        System.out.println("[");
        for (int i = 0; i < matrix.length; i++) {
            System.out.print("  [");
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j]);
                if (j < matrix[i].length - 1) {
                    System.out.print(", ");
                }
            }
            System.out.println("]");
        }
        System.out.println("]");
    }

    // Helper method to print 1D array
    private static void printArray(int[] arr) {
        if (arr == null) {
            System.out.println("null");
            return;
        }
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            if (i < arr.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }
}

Output

Running the main method produces:

Test case 1:
Matrix:
[
  [1, 2, 3]
  [4, 5, 6]
  [7, 8, 9]
]
Main diagonal: [1, 5, 9]
Test case 2:
Matrix:
[
  [5]
]
Main diagonal: [5]
Test case 3:
Matrix:
[
  [-1, -2]
  [-3, -4]
]
Main diagonal: [-1, -4]
Test case 4:
Matrix:
[
  [1, 2, 3, 4]
  [5, 6, 7, 8]
  [9, 10, 11, 12]
  [13, 14, 15, 16]
]
Main diagonal: [1, 6, 11, 16]
Test case 5:
Matrix:
null
Main diagonal: null

Explanation:

  • Test case 1: Extracts diagonal [1, 5, 9] from a 3×3 matrix.
  • Test case 2: Extracts [5] from a 1×1 matrix.
  • Test case 3: Extracts [-1, -4] from a 2×2 matrix with negative numbers.
  • Test case 4: Extracts [1, 6, 11, 16] from a 4×4 matrix.
  • Test case 5: Returns null for a null matrix.

How It Works

  • Step 1: The getMainDiagonal method checks if the matrix is null, empty, or not square. For [[1, 2, 3], [4, 5, 6], [7, 8, 9]], it proceeds.
  • Step 2: Get size: n = 3.
  • Step 3: Create a result array of size 3.
  • Step 4: Iterate for i = 0 to 2:
    • i = 0: result[0] = matrix[0][0] = 1
    • i = 1: result[1] = matrix[1][1] = 5
    • i = 2: result[2] = matrix[2][2] = 9
  • Example Trace: For test case 1, builds [1, 5, 9] by collecting matrix[i][i].
  • Main Method: Tests with square matrices (3×3, 1×1, 2×2, 4×4) and a null matrix, printing inputs and results.
  • Diagonal Property: Collects elements where row index equals column index, creating a 1D array of size n.

Complexity Analysis Table

OperationTime ComplexitySpace Complexity
Diagonal ExtractionO(n)O(n)
Full AlgorithmO(n)O(n)

Note:

  • n is the size of the square matrix (rows = columns).
  • Time complexity: O(n), as the algorithm iterates through n diagonal elements.
  • Space complexity: O(n), for the result array. Temporary variables use O(1) space.
  • Best, average, and worst cases are O(n).

✅ Tip: Since the matrix is square, a single loop over indices i is sufficient to extract matrix[i][i]. Test with various sizes and negative numbers to ensure correctness.

⚠ Warning: Ensure the input matrix is square and not null to avoid NullPointerException or ArrayIndexOutOfBoundsException. Verify consistent row lengths for a well-formed matrix.