Detect Target Pair in Spiral Matrix Order
Arrays & HashingAuto-graded · 17 test casesLast 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
nis an integer between 1 and 100.- Matrix values are integers between -10,000 and 10,000.
kis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires traversing an $n \times n$ matrix in spiral order while checking if any two separate matrix elements add up to a target sum $k$.
-
Spiral Traversal: Maintain four boundary indices (
top,bottom,left,right). Loop through concentric rectangular rings in clockwise order:- Walk left-to-right across the top row, then increment
top. - Walk top-to-bottom down the right column, then decrement
right. - If
top <= bottom, walk right-to-left across the bottom row, then decrementbottom. - If
left <= right, walk bottom-to-top up the left column, then incrementleft.
- Walk left-to-right across the top row, then increment
-
Target Pair Verification: As each cell value $v$ is visited, check if the required complement $k - v$ is stored in a hash set
seenof previously visited values. If it exists, returnTrueimmediately. Otherwise, add $v$ toseen. Checking before adding ensures that an element is not paired with itself (such as a single element matching $k/2$).
Complexity Analysis
- Time Complexity: $O(N)$ where $N = n^2$ is the total number of cells. Each cell is visited at most once, and set lookups/insertions operate in $O(1)$ average time.
- Space Complexity: $O(N)$ to store visited values in the hash set
seen.
Python Reference Solution
from typing import List
def solve_spiral_and_pair_sum(matrix: List[List[int]], k: int) -> bool:
if not matrix or not matrix[0]:
return False
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
seen = set()
while top <= bottom and left <= right:
# Traverse top row left to right
for col in range(left, right + 1):
value = matrix[top][col]
if k - value in seen:
return True
seen.add(value)
top += 1
# Traverse right column top to bottom
for row in range(top, bottom + 1):
value = matrix[row][right]
if k - value in seen:
return True
seen.add(value)
right -= 1
# Traverse bottom row right to left
if top <= bottom:
for col in range(right, left - 1, -1):
value = matrix[bottom][col]
if k - value in seen:
return True
seen.add(value)
bottom -= 1
# Traverse left column bottom to top
if left <= right:
for row in range(bottom, top - 1, -1):
value = matrix[row][left]
if k - value in seen:
return True
seen.add(value)
left += 1
return False