Number of Equal Numbers Blocks - 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 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[index]
  • 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: If you want to test your solution using a custom test, behavior for tests with nums.length > 10 is undefined.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,3,3,2,2]
Output: 3
💡 Note: Three blocks: [1,1], [3,3], [2,2]. Each block contains equal adjacent values.
Example 2 — Single Elements
$ Input: nums = [1,2,3,4]
Output: 4
💡 Note: Four blocks: [1], [2], [3], [4]. Each element forms its own block.
Example 3 — All Same
$ Input: nums = [5,5,5,5,5]
Output: 1
💡 Note: One block: [5,5,5,5,5]. All elements are the same.

Constraints

  • 1 ≤ nums.length ≤ 1015
  • 1 ≤ nums[i] ≤ 100
  • All occurrences of each value are adjacent

Visualization

Tap to expand
Number of Equal Numbers Blocks INPUT nums array: 0 1 2 3 4 5 1 1 3 3 2 2 Block 1 Block 2 Block 3 BigArray Class: at(index) - get value size() - array length Input Values: [1,1,3,3,2,2] ALGORITHM STEPS 1 Initialize count = 0, index = 0 2 Iterate Array While index less than size 3 Find Block End Skip all equal adjacent values using binary search 4 Count Block Increment count, move to next block Block Detection: i=0: val=1, skip to i=2 i=2: val=3, skip to i=4 i=4: val=2, skip to i=6 FINAL RESULT Identified Blocks: Block 1: [1, 1] indices 0-1 Block 2: [3, 3] indices 2-3 Block 3: [2, 2] indices 4-5 Output: 3 OK - 3 maximal blocks found Key Insight: Since all occurrences of a value are adjacent (grouped together), we can use binary search to efficiently find the end of each block. This reduces time complexity from O(n) to O(k log n), where k is the number of blocks. Each block boundary detection uses binary search on BigArray. TutorialsPoint - Number of Equal Numbers Blocks | Optimal Solution
Asked in
Google 15 Facebook 8 Microsoft 6
12.4K Views
Medium Frequency
~15 min Avg. Time
187 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