Solve Subarray Sum and Local Minimum
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Take-home Project
Quick Answer: This question evaluates array algorithm proficiency and complexity analysis by testing the ability to count target-sum contiguous subarrays and to locate a local minimum under a logarithmic-time constraint. It is commonly asked in the Coding & Algorithms domain to measure practical implementation skills and conceptual understanding of algorithmic patterns and time-complexity guarantees.
Part 1: Count Target-Sum Subarrays
Constraints
- 0 <= len(nums) <= 200000
- -10^9 <= nums[i] <= 10^9
- -10^9 <= k <= 10^9
Examples
Input: ([1, 1, 1], 2)
Expected Output:
Explanation: The subarrays [1, 1] at indices (0..1) and (1..2) both sum to 2.
Input: ([1, 2, 3], 3)
Expected Output:
Explanation: The valid subarrays are [1, 2] and [3].
Input: ([3, 4, 7, 2, -3, 1, 4, 2], 7)
Expected Output:
Explanation: There are four valid subarrays whose sum is 7.
Input: ([], 0)
Expected Output:
Explanation: An empty array has no subarrays.
Input: ([1, -1, 0], 0)
Expected Output:
Explanation: The valid subarrays are [1, -1], [0], and [1, -1, 0].
Hints
- Think about prefix sums: if prefix_sum[j] - prefix_sum[i] == k, then the subarray (i+1..j) has sum k.
- Use a hash map to count how many times each prefix sum has appeared so far.
Part 2: Find Any Local Minimum in O(log n)
Constraints
- 1 <= len(nums) <= 200000
- -10^9 <= nums[i] <= 10^9
- nums[i] != nums[i + 1] for all 0 <= i < n - 1
Examples
Input: ([9],)
Expected Output:
Explanation: With one element, index 0 is trivially a local minimum.
Input: ([2, 1, 3],)
Expected Output:
Explanation: nums[1] = 1 is smaller than both neighbors.
Input: ([5, 4, 3, 2, 1],)
Expected Output:
Explanation: The array is strictly decreasing, so the last element is the only local minimum.
Input: ([1, 2, 3, 4],)
Expected Output:
Explanation: The array is strictly increasing, so the first element is the only local minimum.
Input: ([9, 7, 3, 4, 8],)
Expected Output:
Explanation: nums[2] = 3 is smaller than both 7 and 4, so index 2 is a local minimum.
Hints
- First check the boundary cases: the first or last element may already be a local minimum.
- During binary search, if nums[mid] is greater than its left neighbor, then a local minimum must exist on the left side; otherwise it must exist on the right side.