Solve array duplicates and two-type subarray
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: These problems evaluate proficiency with array manipulation, frequency and membership reasoning, and algorithmic analysis of time and space complexity when detecting duplicates and locating longest subarrays constrained by distinct values.
Part 1: Check for Duplicates
Constraints
- 0 <= len(nums) <= 100000
- -1000000000 <= nums[i] <= 1000000000
Examples
Input: [1, 2, 3, 1]
Expected Output: True
Explanation: The value 1 appears more than once.
Input: [1, 2, 3, 4]
Expected Output: False
Explanation: All values are distinct.
Input: []
Expected Output: False
Explanation: An empty array has no duplicates.
Input: [5]
Expected Output: False
Explanation: A single element cannot form a duplicate.
Input: [-10, 7, 0, -10]
Expected Output: True
Explanation: The value -10 appears twice.
Hints
- Try keeping track of values you have already seen as you scan the array once.
- If you encounter a value that is already in your tracking structure, you can return immediately.
Part 2: Longest Subarray With At Most Two Distinct Values
Constraints
- 0 <= len(fruits) <= 100000
- Fruit types are integers and may repeat
- An empty array should return 0
Examples
Input: [1, 2, 1]
Expected Output: 3
Explanation: The whole array contains only two distinct values, so the answer is 3.
Input: [0, 1, 2, 2]
Expected Output: 3
Explanation: The longest valid subarray is [1, 2, 2].
Input: [1, 2, 3, 2, 2]
Expected Output: 4
Explanation: The longest valid subarray is [2, 3, 2, 2].
Input: []
Expected Output: 0
Explanation: No trees means no fruits can be collected.
Input: [3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4]
Expected Output: 5
Explanation: The longest valid subarray is [1, 2, 1, 1, 2], which has length 5.
Hints
- Think about maintaining a sliding window that always contains at most two distinct fruit types.
- Use a frequency map for the current window, and shrink the left side whenever the window contains more than two distinct values.