Problem Description
Given a 0-indexed array where every occurrence of a value appears consecutively, partition the array into maximal blocks (each block contains only one unique number) and return the number of these blocks. Since the array is extremely large, you are only provided access through a BigArray class with functions at(index) and size().
Key Insights
- All equal values in the array are contiguous, which means that a change in value indicates the beginning of a new block.
- Instead of processing each element (which can be infeasible for a huge array), the property allows you to count blocks by detecting value transitions.
- The problem constraints imply a straightforward linear scan is acceptable in practical test cases even though the theoretical limit is up to 10^15 elements.
- Remember to handle the case when the array has only one element.
Space and Time Complexity
Time Complexity: O(n) – We scan the array once from start to finish. Space Complexity: O(1) – Only a constant amount of extra space is used.
Solution
The algorithm starts by retrieving the size of the array from the BigArray instance. If the array is empty (edge case although minimum size is 1), we return 0. Otherwise, initialize a counter (blockCount) to 1. Then, iterate from the second element to the end. For each index, compare the current element with the previous one using the at() function. If they differ, it indicates the start of a new block, so increment the counter. Finally, return the counter as the number of blocks.
The primary data structure used is the provided BigArray instance, which only offers access to elements via the at() method. The algorithm is simple and leverages the property that equal elements are adjacent by design, allowing us to immediately detect block boundaries with a single comparison between consecutive elements.