Number of Senior Citizens — Easy Problem & Solution

Each string in details is a 15-character passenger record: the first ten characters are a phone number; the next character is the passenger's gender; the…

  • Difficulty: Easy
  • Topics: Arrays, Strings
  • Asked at: Amazon, Google, Infosys
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Each string in details is a 15-character passenger record:

  • the first ten characters are a phone number;
  • the next character is the passenger's gender;
  • the next two characters are the age;
  • the final two characters are the seat number.

Return the number of passengers strictly older than 60.

Example 1

Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"]
Output: 2
Explanation: Ages 75, 92 and 40 — the first two clear 60.

Example 2

Input: details = ["1313579440F2036","2921522980M5644"]
Output: 0
Explanation: Ages 20 and 56.

Example 3

Input: details = ["6060606060M6100"]
Output: 1
Explanation: Age 61; exactly 60 would not count.

Constraints

  • 1 <= details.length <= 100
  • details[i].length == 15
  • details[i] consists of digits from '0' to '9'.
  • details[i][10] is either 'M', 'F' or 'O'.
  • The phone numbers and seat numbers of the passengers are distinct.

How to solve Number of Senior Citizens

Every record has a fixed layout, so the age is always the substring at indices 11 and 12. Parse it and count the values above 60.

Approach

  1. For each record, take details[i][11..12].
  2. Convert it to an integer.
  3. Count the values strictly greater than 60.

Why it works

The fixed width is what makes this a slicing problem rather than a parsing one — there are no separators to search for and no variable-length fields. Arithmetic on the two digits ((d1 - '0') * 10 + (d2 - '0')) avoids allocating a substring at all.

Complexity

  • Time — O(n)
  • Space — O(1)

Pitfalls

  • The age begins at index 11, after ten phone digits and one gender character — off by one and you read the gender.
  • Strictly greater than 60: 60 itself does not count.
  • Ages are zero-padded, so "05" must parse as 5, not fail.

Reference solution

Python

from typing import List

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

JavaScript

var countSeniors = function(details) {
    var count = 0;
    for (var i = 0; i < details.length; i++) {
        var age = parseInt(details[i].substring(11, 13), 10);
        if (age > 60) count++;
    }
    return count;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue