108. Matrix Special Elements

Asked in

Matrix Special Elements
Given a matrix, return the number of distinct values that appear as a unique minimum or unique maximum in at least one row or at least one column.

Before counting, verify that in every row and every column, the minimum value occurs exactly once and the maximum value occurs exactly once.
A row or column of length 1 is valid: its single value is both the unique minimum and the unique maximum.
If this condition fails for any row or column, return -1.

Method Signature

int countMatrixSpecialElements(List<String> matrixRows)
  • matrixRows represents the matrix as a 1-D list of strings.
  • Each string represents one row, with comma-separated integers.
  • Return the number of distinct special values.
  • Return -1 if any row or column has a non-unique minimum or maximum.

Input Format

  • Each entry in matrixRows is a row of the matrix.
  • Within each row string, integers are separated by commas.
  • Example: List.of("1,2,3", "4,5,6") represents a 2 x 3 matrix.

Rules

  • A value is considered special if it is the unique minimum or unique maximum in at least one row or at least one column.
  • Count only distinct values, not positions.
  • All row strings must contain the same number of integers.

Constraints

  • 1 ≤ matrixRows.size() ≤ 10^3
  • 1 ≤ number of integers in each row ≤ 10^3
  • Each row string contains valid comma-separated integers.
  • Matrix values can be negative, zero, or positive integers.

Examples

Example 1:
Input:
countMatrixSpecialElements(matrixRows = List.of("1,2", "3,4"))
Output:
4
Explanation:
All row and column minimums and maximums are unique. The distinct special values are {1, 2, 3, 4}.

Example 2:
Input:
countMatrixSpecialElements(matrixRows = List.of("5,1,7", "3,9,2", "8,4,6"))
Output:
7
Explanation:
Row special values: {1, 2, 4, 7, 8, 9}.
Column special values: {1, 2, 3, 7, 8, 9}.
Distinct union: {1, 2, 3, 4, 7, 8, 9}.

Example 3:
Input:
countMatrixSpecialElements(matrixRows = List.of("1,1", "2,3"))
Output:
-1
Explanation:
In the first row, the minimum value 1 appears more than once.

Example 4:
Input:
countMatrixSpecialElements(matrixRows = List.of("2,4", "2,5"))
Output:
-1
Explanation:
In the first column, the minimum value 2 appears more than once.

Example 5:
Input:
countMatrixSpecialElements(matrixRows = List.of("7"))
Output:
1
Explanation:
The value 7 is both the unique minimum and maximum in its row and column. The distinct special values are {7}.




Please use Laptop/Desktop or any other large screen to add/edit code.