Unsafe elements in a matrix

You have a matrix S consisting of N rows and M columns. Let u be the maximum element of the matrix and v be the smallest element of the matrix. If any element whose value is equal to u or v are called unsafe elements and they disfigure the complete row and column of the matrix. More formally, if any element is equal to u or v and contains cell number (x, y), that is, S[x][y]=u or S[x][y]=v are unsafe so that they also disfigure all the cells that have row x or column y and also are unsafe.

Your task is to find the number of safe elements.

Example:

Input:
3 3 8 8 3 6 2 4 12 1 2
Output:
2

Approach

Java

package com.java;

import java.util.HashSet;

public class UnsafeElemINMatrix {

    public static void main(String[] args) {
        int r = 3;
        int c = 3;

        int min = 999999999;
        int max = 0;
        int[][] arr = { { 883 }, { 624 }, { 1212 } };
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                int val = arr[i][j];
                arr[i][j] = val;
                if (val > max) {
                    max = val;
                }
                if (val < min) {
                    min = val;
                }
            }
        }
        int rows = 0;
        HashSet<Integercolumns = new HashSet<Integer>();
        for (int i = 0; i < r; i++) {
            boolean pass = false;
            for (int j = 0; j < c; j++) {
                int val = arr[i][j];
                if (val == max || val == min) {
                    if (!columns.contains(val)) {
                        columns.add(val);
                    }

                    pass = true;
                }
            }
            if (pass) {
                rows++;
            }
        }

        System.out.println((r - rows) * (c - columns.size()));
    }

}


Read Interview Questions

Exception Handling Interview Questions

DBMS Interview Questions Set -1

DBMS Interview Questions Set -2

SQL Interview Question Set -1

SQL Interview Question Set -2

JPA Interview Questions Set -1

JPA Interview Question Set -2

Hibernate Interview Questions

Spring Boot Interview Questions Set 1

Spring Boot Interview Questions Set 2


No comments:

Post a Comment