Solve Matrix Traversal and Pair Sum
Company: Illumio
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in array and matrix manipulation, including spiral traversal with boundary and edge-case handling, index management, hash-based complement lookup for pair-sum, and reasoning about time and space complexity.
Part 1: Traverse a Matrix in Spiral Order
Constraints
- 0 <= m <= 200
- 0 <= n <= 200
- If matrix is non-empty, every row has the same length n.
- -10^9 <= matrix[i][j] <= 10^9
- The algorithm should run in O(m * n) time.
Examples
Input: ([[1, 2, 3], [4, 5, 6], [7, 8, 9]],)
Expected Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation: A square 3 x 3 matrix is traversed around the outside, then the center element is added.
Input: ([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],)
Expected Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Explanation: Handles a non-square matrix with more columns than rows.
Input: ([[1, 2, 3, 4]],)
Expected Output: [1, 2, 3, 4]
Explanation: Single-row matrix is already in spiral order.
Input: ([[1], [2], [3]],)
Expected Output: [1, 2, 3]
Explanation: Single-column matrix is traversed from top to bottom.
Input: ([],)
Expected Output: []
Explanation: Empty matrix has no elements to return.
Hints
- Track four boundaries: top, bottom, left, and right. After traversing one side, move that boundary inward.
- Before traversing the bottom row or left column, check that the boundaries have not crossed to avoid duplicates.
Part 2: Find Two Numbers That Sum to Target Without Sorting
Constraints
- 2 <= len(nums) <= 100000
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
- Exactly one valid pair exists.
- Do not sort or mutate nums.
Examples
Input: ([8, 1, 5, 3, 9], 12)
Expected Output: [3, 4]
Explanation: nums[3] + nums[4] = 3 + 9 = 12.
Input: ([2, 7, 11, 15], 9)
Expected Output: [0, 1]
Explanation: The first two elements sum to 9.
Input: ([3, 3], 6)
Expected Output: [0, 1]
Explanation: Minimum-size input with duplicate values; the two indices must be distinct.
Input: ([-4, 10, 6, 2], 8)
Expected Output: [2, 3]
Explanation: Handles negative and positive values. nums[2] + nums[3] = 6 + 2 = 8.
Input: ([0, -1, 4, 9], -1)
Expected Output: [0, 1]
Explanation: Handles zero and a negative target.
Hints
- For each number x, compute the complement target - x and check whether that complement has appeared earlier.
- Use a hash map from value to index to preserve original indices while achieving O(n) time.