Number of Equal Numbers Blocks - Problem

Imagine you have a massive array where identical values are always grouped together - like sorted books on a shelf! ๐Ÿ“š Your job is to count how many distinct blocks of identical numbers exist.

You're given access to a BigArray class with two methods:

  • at(index) - Returns the value at position index
  • size() - Returns the total length of the array

Key Property: All occurrences of any value are adjacent. If nums[i] == nums[j] and i < j, then every element between them has the same value!

Goal: Count the number of maximal blocks where each block contains only equal values.

Example: [1,1,3,3,3,2,2] has 3 blocks: [1,1], [3,3,3], and [2,2]

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,1,3,3,3,2,2]
โ€บ Output: 3
๐Ÿ’ก Note: Array has 3 distinct blocks: [1,1] (indices 0-1), [3,3,3] (indices 2-4), and [2,2] (indices 5-6). Each block contains only equal values and is maximal.
example_2.py โ€” Single Element
$ Input: nums = [5]
โ€บ Output: 1
๐Ÿ’ก Note: Array contains only one element, forming exactly one block [5].
example_3.py โ€” All Different
$ Input: nums = [1,2,3,4,5]
โ€บ Output: 5
๐Ÿ’ก Note: Each element forms its own block since all elements are different: [1], [2], [3], [4], [5].

Visualization

Tap to expand
Book ABook ABook BBook BBook BBook CBook CTransition 1Transition 2Group 1: Book AGroup 2: Book BGroup 3: Book CLibrary Shelf OrganizationTotal Book Groups: 3
Understanding the Visualization
1
Start Reading
Begin with the first book, initialize block count to 1
2
Compare Titles
Compare each book title with the previous one
3
Count Transitions
When title changes, increment the block counter
4
Continue Reading
Repeat until all books are processed
Key Takeaway
๐ŸŽฏ Key Insight: Since identical values are guaranteed to be grouped together, we only need to detect transitions between adjacent elements to count all blocks efficiently in one pass!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Must read every element once to identify all blocks

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Potentially stores all elements in memory

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 1015
  • -109 โ‰ค nums[i] โ‰ค 109
  • All occurrences of any value are adjacent (grouped together)
  • For testing purposes, arrays with length > 10 have undefined behavior
Asked in
Google 28 Facebook 22 Amazon 18 Microsoft 15 Apple 12
28.4K Views
Medium Frequency
~15 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen