2678. Number of Senior Citizens

Problem Description

You are given an array details, where each element represents information about an individual passenger. The format of this information is a string exactly 15 characters long. Let's break down the content of this string:

  • The first ten characters are the phone number of the passenger.
  • The eleventh character (index 10) represents the passenger's gender.
  • The twelfth and thirteenth characters (indexes 11 and 12) denote the passenger's age.
  • The last two characters (indexes 13 and 14) signify the seat that has been allotted to the passenger.

Your task is to calculate and return the number of passengers who are older than 60 years, purely based on the age data provided within each string.


The intuitive approach to solving this problem relies on understanding the structure of each string in the details array. Since the age of each passenger is located at a specific position within the string (indexes 11 and 12), we can focus entirely on those two characters.

By simply iterating over each string in the details array, we can extract the age part of the string, convert it to an integer, and then check if this age is greater than 60. For each passenger meeting this criterion (age > 60), we would increment our count.

Therefore, the solution consists of traversing each string, extracting the age, converting it to an integer, and applying the comparison operator to tally up all the seniors in the list.

Solution Approach

The solution implementation relies on a simple iteration and counting pattern, a common tactic in problems requiring the counting of elements that satisfy a certain condition. Here, Python's concise list comprehension and the built-in sum function make this task even more straightforward.

The algorithm can be described as follows:

  1. Use a list comprehension to iterate through each string x in the given details array.
  2. For each x, extract the characters that represent the age: x[11:13].
  3. Convert that substring to an integer with int(x[11:13]).
  4. Use a comparison operator > to check if the extracted age is greater than 60.
  5. The result of this comparison will be a boolean value (True if the age is greater than 60, False otherwise).
  6. The list comprehension returns a list of boolean values, which when passed to the sum function, counts the True values since True is considered as 1 and False is 0 in Python.
  7. The final sum represents the total number of passengers over the age of 60.

Here's the list comprehension explained:

1sum(int(x[11:13]) > 60 for x in details)
  • for x in details means we are looping over every element in the details array.
  • int(x[11:13]) is converting the age portion of the string to an integer.
  • int(x[11:13]) > 60 performs the check to see if the age is above 60.

The beauty of this approach lies in its simplicity and Python's ability to handle such operations in one line, demonstrating the power of list comprehensions and the sum function in Python.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's consider the following small example to illustrate the solution approach.

Suppose the details array is as follows:

1details = [
2    "1234567890M658C1",
3    "0987654321F578C2",
4    "5678901234M521C3",
5    "2345678901F411C4",
6    "3456789012M629C5"

Following the solution approach:

  1. We iterate over each string in the details array.
  2. For the first string details[0], we extract the age details[0][11:13] which gives us '65'. We convert this to an integer using int('65'), which is 65.
  3. We check if 65 is greater than 60. It is, so it contributes to our count.
  4. For the second string details[1], the extracted age is '57', which is not greater than 60. Therefore, it doesn't add to the count.
  5. We repeat this process for all elements in the list. Here are the ages:
    • "1234567890M658C1" → Age is 65, count incremented.
    • "0987654321F578C2" → Age is 57, count not incremented.
    • "5678901234M521C3" → Age is 52, count not incremented.
    • "2345678901F411C4" → Age is 41, count not incremented.
    • "3456789012M629C5" → Age is 62, count incremented.
  6. Now we have 2 passengers over the age of 60 from our list.
  7. The sum function would add up the True values (each True representing a passenger above 60) resulting in a final count of 2.

Therefore, when we run this code:

1sum(int(x[11:13]) > 60 for x in details)

It will iterate over the list of details, check ages, and return the sum of True values which corresponds to the number of passengers above the age of 60. In our example, the final count is 2.

Solution Implementation

1class Solution:
2    def countSeniors(self, details: List[str]) -> int:
3        # This method takes a list of strings where each string contains details that include age.
4        # It returns the count of how many details strings represent people older than 60 years.
6        # Initialize a count variable to keep track of the number of seniors
7        senior_count = 0
9        # Iterate over each detail string in the provided list
10        for detail in details:
11            # Extract the age part from the detail string, assuming age is always at the 11th to 13th characters
12            age = int(detail[11:13])
14            # Check if the extracted age is greater than 60
15            if age > 60:
16                # If true, increment the senior count
17                senior_count += 1
19        # Return the total count of seniors
20        return senior_count
22# Note: You'd still need to import List from the typing module 
23# for the type annotation to work: from typing import List
1class Solution {
2    // Method to count the number of seniors based on their age details.
3    public int countSeniors(String[] details) {
4        // Initialize a counter for seniors.
5        int seniorCount = 0;
7        // Loop through all the provided age details.
8        for (String detail : details) {
9            // Extract the age from the current detail string.
10            // Assuming the age is always in the same position (index 11 to 13).
11            int age = Integer.parseInt(detail.substring(11, 13));
13            // Check if the age is greater than 60 to determine if the person is a senior.
14            if (age > 60) {
15                // Increment the count for seniors.
16                seniorCount++;
17            }
18        }
20        // Return the final count of seniors.
21        return seniorCount;
22    }
1#include <vector>
2#include <string>
4class Solution {
6    // Counts the number of seniors based on their age found in details.
7    // Assumes that details contain an age starting at the 12th character of each string.
8    int countSeniors(vector<string>& details) {
9        int seniorCount = 0; // Initialize a count of seniors
11        // Iterate over each string in the details vector
12        for (const auto& detail : details) {
13            // Extract the age from the string. Assuming that the age
14            // starts at the 12th character (index 11) and is 2 digits long.
15            int age = stoi(detail.substr(11, 2));
17            // Increment the senior count if the age is greater than 60
18            seniorCount += (age > 60) ? 1 : 0;
19        }
21        // Return the total count of seniors
22        return seniorCount;
23    }
26// Note: This code assumes that the 'details' vector and each string within it are properly formatted,
27// with the age starting at the 12th character and being two characters long.
1// Function to count the number of seniors in a list of details
2function countSeniors(details: string[]): number {
3    // Initialize the count of seniors
4    let seniorCount = 0;
6    // Loop through each detail string in the details array
7    for (const detail of details) {
8        // Extract the age part of the detail string by slicing from
9        // the 12th character to the 14th (zero indexed)
10        const age = parseInt(detail.slice(11, 13));
12        // If the age is greater than 60, increment the senior count
13        if (age > 60) {
14            seniorCount++;
15        }
16    }
18    // Return the total count of seniors
19    return seniorCount;

Time and Space Complexity

The time complexity of the code is O(n), where n is the length of the details list. This is because the code iterates over each element of the list exactly once when performing the sum, and the string slicing and integer comparison for each element are constant time operations.

The space complexity of the code is O(1), indicating that the amount of additional memory used does not depend on the size of the input list. The only extra space used is for the cumulative sum and temporary variables for the string slicing and the integer comparison, all of which require a constant amount of space.

Learn more about how to find time and space complexity quickly using problem constraints.

Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which of the following is a good use case for backtracking?

Recommended Readings

Got a question? Ask the Monster Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.

Coding Interview Strategies

Dive into our free, detailed pattern charts and company guides to understand what each company focuses on.

See Patterns