⚡Flashcard Drill➔
NeetCode #35LC-2678EasyArrays & Hashing
← Back to All Problems

#35 · #2678 · Number of Senior Citizens(老人的数目)

📌 Problem Statement & Constraints

Given an array details of passenger information strings, each formatted as "<phone number><gender><age><seat>", return the number of passengers who are strictly over 60 years old. The age occupies fixed character positions 11 and 12. Constraints: 1 <= details.length <= 100, details[i].length == 15.

💡 Core Algorithmic Approaches

  1. Because every string has the same fixed layout, the age is always at indices 11 and 12 (0-based).
  2. Slice those two characters and convert to an integer.
  3. Count how many exceed 60.
  4. Splitting on spaces is a valid alternative, but the fixed-width slice is O(1) per string and directly reflects the stated format.

💻 Benchmark Python3 Implementation

class Solution:
    def countSeniors(self, details: List[str]) -> int:
        return sum(1 for d in details if int(d[11:13]) > 60)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one slice and comparison per passenger.
💾 Space Complexity
O(1): a single accumulator.

⚠️ Interview Pitfalls & Follow-ups

  • Using >= 60: the problem says strictly over 60, so 60 itself does not count.
  • Guessing the wrong slice indices: the phone number is 10 digits, then the gender is 1 character, so the age starts at index 11 and spans two characters.
  • Splitting on spaces and indexing the wrong field: the format is fixed-width, and the phone number contains no spaces, so the slice is more robust than a split-based parse here.
⚡
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

中文速览与面试要点

老人的数目

给你一个下标从 0 开始的字符串数组 details,其中每个元素是一个长度为 15 的字符串,格式为:前 10 个字符是电话号码,接下来 1 个字符是性别(M 或 F),接下来 2 个字符是年龄,最后 3 个字符是座位号。请你返回年龄 严格大于 60 岁的人数。约束:1 ≤ details.length ≤ 100;每个 details[i].length == 15。

核心要点

  • 按固定下标切片 :年龄字段位于下标 11 到 12(含),因此 details[i][11:13] 即年龄字符串,转 int 后与 60 比较。
  • 为什么用切片而非正则 :格式固定且字段位置明确,切片是 O(1) 且最直观的解析方式。
  • 统计写法 :用生成器表达式配合 sum ,一行完成计数。
  • 本题定位 :字符串解析类的基础题,考察对固定宽度格式的理解与下标计算。

常见陷阱

  • 下标算错 :常见错误是取 d[10:12] (把性别也切进来)或 d[12:14] (切到座位号)。必须数准:前 10 位电话 + 1 位性别 = 年龄从下标 11 开始,占 2 位。
  • 比较写成 &gt;= 60 :题目要求 严格大于 60 岁,恰好 60 岁不计入。
  • 忘记转 int 而直接字符串比较 :字符串比较 "9" &gt; "60" 为 True,结果完全错误。

参考实现

class Solution:
    def countSeniors(self, details: list[str]) -> int:
        # 格式:电话(0-9) 性别(10) 年龄(11-12) 座位(13-14)
        return sum(1 for d in details if int(d[11:13]) > 60)