⚡Flashcard Drill➔
NeetCode #16LC-1426EasyArrays & HashingNC Algo100
← Back to All Problems

#16 · #1426 · Counting Elements(数元素)

📌 Problem Statement & Constraints

Given an integer array arr, count how many elements x exist such that x + 1 is also present in arr. If duplicates of x exist, count each of them. Constraints: 1 <= arr.length <= 1000, 0 <= arr[i] <= 1000.

💡 Core Algorithmic Approaches

  1. The question is a membership test, so a hash set of the array gives O(1) lookups.
  2. Iterate the original array (not the set), because duplicates must each be counted.
  3. For each x, add 1 to the answer if x + 1 is in the set.
  4. Using the set as the iteration source would undercount duplicates -- a subtle but common slip.

💻 Benchmark Python3 Implementation

class Solution:
    def countElements(self, arr: List[int]) -> int:
        s = set(arr)
        return sum(1 for x in arr if x + 1 in s)   # iterate arr, not s

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass to build the set, one pass to count.
💾 Space Complexity
O(n) for the set. A sort-based solution would be O(n log n) time with O(1) extra space.

⚠️ Interview Pitfalls & Follow-ups

  • Iterating the set instead of the array: [1, 1, 2] should count both 1s, giving 2; iterating the set yields only 1.
  • Checking x - 1: the problem asks about x + 1.
  • Forgetting that arr[i] can be 0: 0 + 1 = 1 is a valid lookup, no special case needed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

数元素

给你一个整数数组 arr,请你统计其中满足以下条件的元素 x 的个数:x + 1 也在 arr 中。注意:如果 arr 中有重复元素,它们应当被 分别计数 。约束:1 ≤ arr.length ≤ 1000;0 ≤ arr[i] ≤ 1000。

核心要点

  • 集合 + 一次遍历(标准解) :先把 arr 全部放入集合,然后遍历 arr 中每个元素 x,若 x + 1 在集合中则计数加一。
  • 为什么必须遍历原数组而不是集合 :重复元素要分别计数。例如 [1,1,2] 中两个 1 都满足条件,答案是 2;若遍历集合只会得到 1。
  • 计数法(替代解) :用 Counter 统计频率,对每个存在的值 v,若 v+1 也存在,则答案加上 freq[v]。与集合法等价。
  • 值域数组 :arr[i] ≤ 1000,可用布尔数组替代集合,常数更小。

常见陷阱

  • 遍历集合而非原数组 :这是本题第一大坑。写成 sum(1 for x in present if x+1 in present) 会丢失重复元素的计数。
  • 用 x + 1 in arr 直接判断 : in 对列表是 O(n) 查找,整体退化为 O(n^2),必须先用集合或哈希表做 O(1) 查找。
  • 误以为 x 必须出现多次才算 :题目只要求 x+1 存在,对 x 自身的出现次数没有限制。

参考实现

class Solution:
    def countElements(self, arr: list[int]) -> int:
        present = set(arr)
        # 必须遍历原数组:重复元素要分别计数
        return sum(1 for x in arr if x + 1 in present)

# 计数法(结果等价,思路更贴近「分别计数」的字面含义):
# from collections import Counter
# cnt = Counter(arr)
# return sum(c for v, c in cnt.items() if v + 1 in cnt)