Number of Equal Numbers Blocks — LeetCode 2936 Python Solution
MediumLeetCode PremiumArrayBinary SearchInteractive
- Problem
- #2936
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 0-indexed array of integers, nums. The following property holds for nums: All occurrences of a value are adjacent.
Example
- Input
- nums = [3,3,3,3,3]
- Output
- 1
- Explanation
- There is only one block here which is the whole array (because all numbers are equal) and that is: [3,3,3,3,3]. So the answer would be 1.
Python solution
Python
# Definition for BigArray.
# class BigArray:
# def at(self, index: long) -> int:
# pass
# def size(self) -> long:
# pass
class Solution(object):
def countBlocks(self, nums: Optional["BigArray"]) -> int:
i, n = 0, nums.size()
ans = 0
while i < n:
ans += 1
x = nums.at(i)
if i + 1 < n and nums.at(i + 1) != x:
i += 1
else:
i += bisect_left(range(i, n), True, key=lambda j: nums.at(j) != x)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times \log n), where m is the number of different elements in the array num, and n is the length of the array num |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2936. Number of Equal Numbers Blocks is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2936. Number of Equal Numbers Blocks?
- LeetCode 2936. Number of Equal Numbers Blocks is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2936. Number of Equal Numbers Blocks?
- The Python solution on this page runs in O(m \times \log n), where m is the number of different elements in the array num, and n is the length of the array num.
- What is the space complexity of LeetCode 2936. Number of Equal Numbers Blocks?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2936. Number of Equal Numbers Blocks cover?
- LeetCode 2936. Number of Equal Numbers Blocks is tagged Array, Binary Search and Interactive on LeetCode.
- Is LeetCode 2936. Number of Equal Numbers Blocks a premium problem?
- Yes. LeetCode 2936. Number of Equal Numbers Blocks is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.