Count Integers Appearing in a Single Block Problem
#4038
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 4038.
You are given an integer array nums.
An integer x is special if all occurrences of x in nums appear in a single contiguous block.
Return the number of distinct special integers in nums.
Example 1:
Input: nums = [1,2,2,1]
Output: 1
Explanation:
- 1 appears at indices 0 and 3, forming two separate blocks, so it is not special.
- 2 appears in a single contiguous block at indices [1, 2], so it is special.
Therefore, there is one special integer.
Example 2:
Input: nums = [3,3,1,2,2,1]
Output: 2
Explanation:
- 3 appears in a single contiguous block at indices [0, 1], so it is special.
- 1 appears at indices 2 and 5, forming two separate blocks, so it is not special.
- 2 appears in a single contiguous block at indices [3, 4], so it is special.
Therefore, there are two special integers.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Count the blocks of each value
Call a maximal run of equal consecutive elements a block. A value is special exactly when it forms a single block.
Scan the array; position i starts a new block when i = 0 or nums[i] != nums[i - 1], and we then increment cnt[nums[i]]. At the end, the answer is the number of values whose block count is exactly 1.
Complexity: time O(n + M), space O(M), where n = nums.length and M = 100 is the largest value.
from collections import Counter
class Solution:
def countSpecialIntegers(self, nums: List[int]) -> int:
cnt = Counter(x for i, x in enumerate(nums) if i == 0 or x != nums[i - 1])
return sum(v == 1 for v in cnt.values())