Find Index Pairs of Matching Elements in Arrays
Company: Walmart Labs
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates the ability to work with sorted arrays, index mapping, duplicate handling, and reasoning about correctness and algorithmic complexity.
Find Index Pairs of Matching Elements in Sorted Arrays
Constraints
- Both arrays are sorted in non-decreasing order.
- Within each array all values are distinct (no duplicates).
- Either array may be empty.
- Values may be negative.
Examples
Input: ([1,4,5,6,7,9], [1,2,3,6,9])
Expected Output: [[0, 0], [3, 3], [5, 4]]
Explanation: Matches at value 1 (0,0), value 6 (3,3), value 9 (5,4).
Input: ([], [1,2,3])
Expected Output: []
Explanation: First array empty -> no pairs.
Hints
- Walk both arrays with two pointers i and j, advancing the pointer at the smaller value.
- When arr1[i] == arr2[j], record [i, j] and advance BOTH pointers.
- Because there are no duplicates, you never need to look back — the merge is strictly O(n + m).
Index Pairs of Matching Elements With Duplicates
Constraints
- Both arrays are sorted in non-decreasing order.
- Arrays may contain duplicate values.
- Either array may be empty.
- Values may be negative.
- Output may be large (up to the product of the run lengths for a shared value).
Examples
Input: ([1,1,4,5,6,6,6,7,9], [1,2,3,6,6,9,9])
Expected Output: [[0, 0], [1, 0], [4, 3], [4, 4], [5, 3], [5, 4], [6, 3], [6, 4], [8, 5], [8, 6]]
Explanation: Value 1: 2x1=2 pairs; value 6: 3x2=6 pairs; value 9: 1x2=2 pairs.
Input: ([1,4,5,6,7,9], [1,2,3,6,9])
Expected Output: [[0, 0], [3, 3], [5, 4]]
Explanation: No duplicates -> reduces to the basic case.
Hints
- Still merge with two pointers, but when the values are equal, find the FULL run of that value in each array.
- Emit the Cartesian product of the arr1 index run and the arr2 index run, then advance both pointers past their runs.
- Iterating the arr1 run in the outer loop and arr2 run in the inner loop yields pairs already sorted by (i, j).