Contents

Special two-dimensional array 2 (with.Java)

   Dec 3, 2023     2 min read

This is the “Special Two-Dimensional Array 2” problem.

We’re going to learn about it by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Let’s start with the problem

Problem

Given a two-dimensional array arr of size n × n as a parameter, write a solution function that returns 1 if arr satisfies the following and 0 otherwise.

arr[i][j] = arr[j][i] for any integer i, j such that 0 ≤ i, j < n.

Example input and output

arrresult
[[5, 192, 33], [192, 72, 95], [33, 95, 999]]1
[[19, 498, 258, 587], [63, 93, 7, 754], [258, 7, 1000, 723], [587, 754, 723, 81]]0

My solution to the ### problem

class Solution {
    public int solution(int[][] arr) {
        int answer = 0;
        for(int i = 0; i < arr.length - 1; i++){
            for(int j = 0; j < arr.length; j++){
                if(arr[i][j] != arr[j][i]){
                    return answer;
                }
            }
        }
        answer = 1;
        return answer;
    }
}

Solution

int answer = 0; : Initialize the variable answer to store the resulting value.

for(int i = 0; i < arr.length - 1; i++) : Iterates over the two-dimensional array, checking only the top half relative to the main diagonal. (arr.length is the size of the array.)

for(int j = 0; j < arr.length; j++) : Checks for symmetry by comparing the elements for the current row i and column j with the elements for column i and row j.

if(arr[i][j] != arr[j][i]) : if the current element and the element at the symmetric position are different (if not symmetric):

Set answer to 0, and exit the function.

answer = 1;: if all elements are symmetric, set answer to 1.

return answer;: Return the result, the value of answer.