Problem
You are given a 0-indexed array of integers, nums
. The following property holds for nums
:
- All occurrences of a value are adjacent. In other words, if there are two indices
i < j
such thatnums[i] == nums[j]
, then for every indexk
thati < k < j
,nums[k] == nums[i]
.
Since nums
is a very large array, you are given an instance of the class
BigArray
which has the following functions:
int at(long long index)
: Returns the value ofnums[i]
.void size()
: Returnsnums.length
.
Let’s partition the array into maximal blocks such that each block contains equal values. Return the number of these blocks.
Note that if you want to test your solution using a custom test, behavior for tests with nums.length > 10
is undefined.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= nums.length <= 1015
1 <= nums[i] <= 10^9
- The input is generated such that all equal values are adjacent.
- The sum of the elements of
nums
is at most1015
.
Solution
Method 1 – Binary Search for Block Boundaries
Intuition
Since all equal values are adjacent, each block is a contiguous segment of equal values. We can find the start of each block by moving to the next index where the value changes, using binary search to jump to the end of the current block efficiently.
Approach
- Start at index 0. For each block, use binary search to find the last index of the current value.
- Move to the next index and repeat until the end of the array.
- Count the number of blocks.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(B*log N)
, where B is the number of blocks and N is the array size. - 🧺 Space complexity:
O(1)
.