Solve both coding tasks.
Task 1: Track the first non-repeated number in a stream
Design a data structure that supports a stream of integers.
Implement the following operations:
-
FirstUnique(int[] nums)
: initializes the data structure with the given initial stream values, in order.
-
int showFirstUnique()
: returns the first integer in insertion order that has appeared exactly once so far. If no such integer exists, return
-1
.
-
void add(int value)
: appends
value
to the stream.
Example:
Input:
FirstUnique([2, 3, 5])
showFirstUnique() -> 2
add(5)
showFirstUnique() -> 2
add(2)
showFirstUnique() -> 3
add(3)
showFirstUnique() -> -1
Design the data structure so that each operation is efficient for a long stream.
Task 2: Find the longest bounded-difference subarray
Given an integer array nums and an integer limit, return the length of the longest contiguous subarray such that the absolute difference between any two elements in the subarray is less than or equal to limit.
Equivalently, for a subarray nums[l..r], it is valid if:
max(nums[l..r]) - min(nums[l..r]) <= limit
Example:
Input: nums = [8, 2, 4, 7], limit = 4
Output: 2
Explanation: The longest valid subarray is [2, 4].
Input: nums = [10, 1, 2, 4, 7, 2], limit = 5
Output: 4
Explanation: The longest valid subarray is [2, 4, 7, 2].