KatInterview

Detect Target Pair in Spiral Matrix Order

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarrayshash-tablematrix

Last updated

Determine if two distinct cells in a 2D matrix sum to a target integer while processing elements in spiral order.

Given a 2D integer matrix of size n x n and a target value k, iterate through the matrix elements in clockwise spiral sequence starting from the top-left cell ([0][0]).

Determine whether there exist two distinct matrix positions whose entries add up to k. Return True if such a pair exists, and False otherwise.

Constraints

  • n is an integer between 1 and 100.
  • Matrix values are integers between -10,000 and 10,000.
  • k is an integer between -20,000 and 20,000.

Examples

Example 1

Input: solve_spiral_and_pair_sum([[1, 2], [3, 4]], 7)

Output: True

Example 2

Input: solve_spiral_and_pair_sum([[1, 1], [1, 1]], 3)

Output: False

Hints

Hint 1

Consider how to traverse a matrix layer by layer using four boundary pointers: top, bottom, left, and right.

Hint 2

To check if any pair sums to `k`, keep track of previously encountered values in a hash set.

Hint 3

Check whether `k - current_value` is present in the hash set before adding `current_value` to prevent pairing an element with itself.