Solve Two Sorted-Array Tasks
Company: Instacart
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates competency in array manipulation, handling of sorted data, search techniques and algorithmic complexity analysis, focusing on skills such as leveraging sorted order and reasoning about time and space trade-offs.
Part 1: Sorted Values, Return Sorted Squares
Constraints
- 0 <= len(nums) <= 100000
- -10000 <= nums[i] <= 10000
- `nums` is sorted in non-decreasing order
Examples
Input: ([-7, -3, 0, 2, 5],)
Expected Output: [0, 4, 9, 25, 49]
Explanation: Squaring gives [49, 9, 0, 4, 25], which sorted becomes [0, 4, 9, 25, 49].
Input: ([],)
Expected Output: []
Explanation: Edge case: an empty input array has no squares.
Input: ([-5],)
Expected Output: [25]
Explanation: Edge case: a single negative value squares to a positive value.
Input: ([-4, -1, 0, 3, 10],)
Expected Output: [0, 1, 9, 16, 100]
Explanation: The largest square comes from 10, then -4, while 0 remains smallest.
Input: ([-9, -7, -3, -1],)
Expected Output: [1, 9, 49, 81]
Explanation: All numbers are negative, so their squares are in reverse order of the original array.
Hints
- The largest square may come from either the most negative number or the most positive number.
- Try using two pointers from both ends of the array and fill the result from right to left.
Part 2: Find the First and Last Position of a Target
Constraints
- 0 <= len(nums) <= 100000
- -1000000000 <= nums[i] <= 1000000000
- -1000000000 <= target <= 1000000000
- `nums` is sorted in non-decreasing order
Examples
Input: ([1, 2, 2, 2, 3, 5], 2)
Expected Output: [1, 3]
Explanation: The target 2 starts at index 1 and ends at index 3.
Input: ([], 4)
Expected Output: [-1, -1]
Explanation: Edge case: an empty array cannot contain the target.
Input: ([5], 5)
Expected Output: [0, 0]
Explanation: Edge case: the only element is the target, so first and last positions are both 0.
Input: ([1, 3, 5, 7], 4)
Expected Output: [-1, -1]
Explanation: The target 4 does not exist in the array.
Input: ([2, 2, 2, 2], 2)
Expected Output: [0, 3]
Explanation: All elements are the target, so the range spans the entire array.
Hints
- Because the array is sorted, you can use binary search instead of scanning linearly.
- Find the first index where a value is at least `target`, and the first index where a value is greater than `target`.