#2936
Medium Algorithms Number of equal numbers blocks
Array Binary Search Interactive
62.5% acceptance
Mar 31, 2026
24
8
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 that nums[i] == nums[j], then for every index k that i < 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 of nums[i].
void size(): Returns nums.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.
Solution
Rust
Time O(n²)
Space O(1)
/**
* Definition for BigArray.
* impl BigArray {
* pub fn new(elements: Vec<i32>) -> Self {}
* pub fn at(&self, usize) -> i32 {}
* pub fn size(&self) -> usize {}
* }
*/
impl Solution {
pub fn count_blocks(nums: BigArray) -> i32 {
let n = nums.size();
if n == 0 {
return 0;
}
let mut count = 0;
let mut i = 0usize;
while i < n {
let val = nums.at(i);
let mut lo = i;
let mut hi = n - 1;
while lo < hi {
let mid = lo + (hi - lo + 1) / 2;
if nums.at(mid) == val {
lo = mid;
} else {
hi = mid - 1;
}
}
count += 1;
i = lo + 1;
}
count
}
}