Number of Senior Citizens

Easy · Arrays & Hashing · Explanation and code example

Character-Based Extraction

How it works

Instead of creating a substring and parsing it, we can directly extract the two digit characters and compute the age mathematically. By subtracting the ASCII value of '0' from each character, we get the numeric value of that digit. The tens digit is at index 11 and the ones digit is at index 12. Combining them gives us the age without any string allocation overhead.

Steps

  1. Initialize a counter res to 0.
  2. For each detail string d:
    • Get the character at index 11 and convert to its numeric value: ten = d[11] - '0'.
    • Get the character at index 12 and convert to its numeric value: one = d[12] - '0'.
    • Compute age = 10 * ten + one.
    • If age > 60, increment res.
  3. Return res.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Things to watch for

Off-By-One Index Errors

The age is located at indices 11 and 12 (0-indexed). A common mistake is using the wrong indices, such as 10 and 11, or forgetting that substring methods in many languages use exclusive end indices. Always verify the exact positions based on the problem's string format specification.

Using Greater-Than-Or-Equal Instead of Greater-Than

The problem asks for passengers strictly older than 60, not 60 or older. Using >= 60 instead of > 60 will incorrectly count 60-year-olds as senior citizens.

Python code example

from typing import List

class Solution:
    def countSeniors(self, details: List[str]) -> int:
        res = 0
        for d in details:
            ten = ord(d[11]) - ord("0")
            one = ord(d[12]) - ord("0")
            age = one + 10 * ten
            if age > 60:
                res += 1
        return res

C++ code example

class Solution {
public:
    int countSeniors(vector<string>& details) {
        int res = 0;
        for (const string& d : details) {
            int ten = d[11] - '0';
            int one = d[12] - '0';
            int age = one + 10 * ten;
            if (age > 60) {
                res++;
            }
        }
        return res;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations