Counting Elements — LeetCode 1426 Python Solution
EasyLeetCode PremiumArrayHash Table
- Problem
- #1426
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. If there are duplicates in arr, count them separately.
Example
- Input
- arr = [1,2,3]
- Output
- 2
- Explanation
- 1 and 2 are counted cause 2 and 3 are in arr.
Python solution
Python
class Solution:
def countElements(self, arr: List[int]) -> int:
cnt = Counter(arr)
return sum(v for x, v in cnt.items() if cnt[x + 1])Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1426. Counting Elements is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1426. Counting Elements?
- LeetCode 1426. Counting Elements is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1426. Counting Elements?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1426. Counting Elements?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1426. Counting Elements cover?
- LeetCode 1426. Counting Elements is tagged Array and Hash Table on LeetCode.
- Is LeetCode 1426. Counting Elements a premium problem?
- Yes. LeetCode 1426. Counting Elements is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.