FastPrepUnique Pairs in a 2D Matrix Summing to Target
Problems/Unique Pairs in a 2D Matrix Summing to Target

Unique Pairs in a 2D Matrix Summing to Target

Amazon logoAmazon● EasyFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source asks for the count of unique pairs in a unique-valued 2D matrix that sum to a target but leaves pair orientation and self-pair rules unstated. The judged task counts unordered pairs from two distinct cells exactly once; with that explicit convention, it matches the source at about 92%.

Given a rectangular integer matrix matrix whose values are globally unique and an integer target, return the number of unordered pairs of values whose sum is target.

Each pair must use two different cells. Count a value pair once regardless of order.

Function

countPairs(matrix: int[][], target: int) → int

Examples

Example 1

matrix = [[1,5],[7,-1]]target = 6return = 2

The unordered pairs are (1, 5) and (-1, 7).

Example 2

matrix = [[1,2],[3,4]]target = 5return = 2

The pairs are (1, 4) and (2, 3).

Example 3

matrix = [[4]]target = 8return = 0

The one value cannot be paired with its own cell.

Constraints

  • 1 <= matrix.length, matrix[i].length.
  • The matrix is rectangular and contains at most 100000 cells.
  • -10^9 <= matrix[i][j], target <= 10^9.
  • All matrix values are distinct.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
class Solution {
    public int countPairs(int[][] matrix, int target) {
      // write your code here
    }
}
Checking account…