Find a Bounded Subarray and Largest Square
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates array manipulation and algorithmic problem-solving skills across two tasks: enforcing bounded value ranges within contiguous subarrays and identifying largest uniform square regions in binary matrices, exercising concepts such as range-tracking, efficient data structures, and dynamic programming.
Part 1: Longest Bounded-Range Subarray
Constraints
- 1 <= len(nums) <= 100000
- -1000000000 <= nums[i] <= 1000000000
- 0 <= limit <= 1000000000
Examples
Input: ([8, 2, 4, 7], 4)
Expected Output: 2
Explanation: The longest valid subarrays are `[2, 4]` and `[4, 7]`, both of length 2.
Input: ([10, 1, 2, 4, 7, 2], 5)
Expected Output: 4
Explanation: The subarray `[2, 4, 7, 2]` has max 7, min 2, and difference 5, so the answer is 4.
Input: ([4, 2, 2, 2, 4, 4, 2, 2], 0)
Expected Output: 3
Explanation: With limit 0, all values in the subarray must be equal. The longest such run is `[2, 2, 2]`.
Input: ([], 3)
Expected Output: 0
Explanation: An empty array has no subarrays, so the longest valid length is 0.
Input: ([5], 0)
Expected Output: 1
Explanation: A single-element subarray always satisfies the condition.
Input: ([-1, -5, -3, -4, -2], 3)
Expected Output: 4
Explanation: The subarray `[-5, -3, -4, -2]` has max -2 and min -5, so the difference is 3 and the length is 4.
Hints
- A sliding window is a good fit because the subarray must be contiguous.
- To expand and shrink the window efficiently, maintain the current minimum and maximum using monotonic deques.
Part 2: Largest Square Area in a Binary Grid
Constraints
- 1 <= m, n <= 300
- grid[i][j] is either 0 or 1
Examples
Input: ([[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]],)
Expected Output: 4
Explanation: The largest all-1 square has side length 2, so its area is 2 * 2 = 4.
Input: ([[0,1],[1,0]],)
Expected Output: 1
Explanation: There is no 2x2 square of 1s, but there are individual 1 cells, so the largest area is 1.
Input: ([[0,0,0],[0,0,0]],)
Expected Output: 0
Explanation: There are no 1s in the grid, so no valid square exists.
Input: ([],)
Expected Output: 0
Explanation: An empty grid contains no square of 1s.
Input: ([[1,1,1],[1,1,1],[1,1,1]],)
Expected Output: 9
Explanation: The entire 3x3 grid is filled with 1s, so the largest square has area 3 * 3 = 9.
Hints
- Think about the largest square that can end at each cell.
- If a cell contains 1, its square size depends on the top, left, and top-left neighboring cells.