Number of Equal Numbers Blocks Problem
Description
LeetCode Problem 2936.
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 < jsuch thatnums[i] == nums[j], then for every indexkthati < 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].long long 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.
Example 1:
Input: nums = [3,3,3,3,3]
Output: 1
Explanation: There is only one block here which is the whole array (because all numbers are equal) and that is: [3,3,3,3,3]. So the answer would be 1.
Example 2:
Input: nums = [1,1,1,3,9,9,9,2,10,10]
Output: 5
Explanation: There are 5 blocks here:
Block number 1: [1,1,1,3,9,9,9,2,10,10]
Block number 2: [1,1,1,3,9,9,9,2,10,10]
Block number 3: [1,1,1,3,9,9,9,2,10,10]
Block number 4: [1,1,1,3,9,9,9,2,10,10]
Block number 5: [1,1,1,3,9,9,9,2,10,10]
So the answer would be 5.
Example 3:
Input: nums = [1,2,3,4,5,6,7]
Output: 7
Explanation: Since all numbers are distinct, there are 7 blocks here and each element representing one block. So the answer would be 7.
Constraints:
1 <= nums.length <= 10^151 <= nums[i] <= 10^9- The input is generated such that all equal values are adjacent.
- The sum of the elements of
numsis at most10^15.
Solution
Approach: Binary Search for Each Block's End
Equal values are adjacent, so every block is a run of one value. Instead of visiting each element, jump from the start of a block straight to its end.
Start at index i = 0. Binary search for the first index j where the value differs from nums[i]; because the run is contiguous, the values equal to nums[i] form a prefix of [i, n), which makes the search valid. Count one block, set i = j, and repeat until i reaches n.
Complexity: O(m log n) time and O(1) extra space, where m is the number of blocks and n is the array length.
# Definition for BigArray.
# class BigArray:
# def at(self, index: long) -> int:
# pass
# def size(self) -> long:
# pass
class Solution(object):
def countBlocks(self, nums: Optional["BigArray"]) -> int:
n = nums.size()
ans = 0
i = 0
while i < n:
ans += 1
x = nums.at(i)
l, r = i, n
while l < r:
mid = (l + r) // 2
if nums.at(mid) != x:
r = mid
else:
l = mid + 1
i = l
return ans