Talentd
FleetCode

4038. Count Integers Appearing in a Single Block

Easy44.4% acceptance

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 <= 100
  • 1 <= nums[i] <= 100

Hints open one at a time

Hint 1
For each distinct value x, let l and r be its first and last positions. All occurrences of x form one contiguous block exactly when r - l + 1 equals the frequency of x.
6:44
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def countSpecialIntegers(self, nums: list[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,2,2,1]
Input
[3,3,1,2,2,1]
Your code is saved on this device.Solution