2678. Number of Senior Citizens
Problem Description
You are given a 0-indexed
array of strings called details
. Each string in this array contains passenger information compressed into exactly 15 characters with a specific format:
- Characters 0-9 (first 10 characters): Phone number
- Character 10 (11th character): Gender
- Characters 11-12 (12th and 13th characters): Age (two-digit number)
- Characters 13-14 (last 2 characters): Seat number
Your task is to count how many passengers are strictly more than 60 years old.
For example, if a string is "9876543210M65A1"
, the passenger's phone number is "9876543210"
, gender is "M"
, age is 65
, and seat is "A1"
. Since 65 > 60, this passenger would be counted.
The solution extracts characters at positions 11 and 12 (using x[11:13]
) to get the age portion, converts it to an integer, and checks if it's greater than 60. The sum()
function counts all passengers meeting this criteria by treating True
as 1 and False
as 0.
Intuition
Since each passenger's information follows a fixed format where the age always appears at the same position (characters 11-12), we don't need to parse the entire string or use complex string manipulation. We can directly access the age portion using string slicing.
The key insight is that Python's string slicing x[11:13]
gives us exactly the two characters representing the age. Converting this substring to an integer allows us to perform the numerical comparison > 60
.
Instead of using a traditional loop with a counter variable, we can leverage Python's generator expression combined with sum()
. When we write sum(int(x[11:13]) > 60 for x in details)
, each comparison int(x[11:13]) > 60
produces a boolean value (True
or False
). Python treats True
as 1 and False
as 0 when summing, effectively counting how many passengers meet our age criterion.
This approach is both concise and efficient - we make a single pass through the array, extract only the necessary information (the age), and count in one expression without maintaining explicit state or counter variables.
Solution Approach
The solution uses a simple traversal and counting approach. We iterate through each string x
in the details
array and extract the age information from the fixed positions.
For each passenger string x
:
- Extract the substring from index 11 to 13 (exclusive) using
x[11:13]
, which gives us the two-character age representation - Convert this substring to an integer using
int()
- Check if the age is greater than 60
The implementation uses a generator expression inside the sum()
function:
sum(int(x[11:13]) > 60 for x in details)
This works because:
- The generator expression
(int(x[11:13]) > 60 for x in details)
produces a sequence of boolean values - Each boolean is
True
if the passenger's age > 60, otherwiseFalse
- The
sum()
function treatsTrue
as 1 andFalse
as 0 - Therefore,
sum()
effectively counts the number ofTrue
values, giving us the total count of seniors
The time complexity is O(n)
where n
is the number of passengers, as we visit each string once. The space complexity is O(1)
since we only use a constant amount of extra space for the counting operation.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a small example with details = ["7868190130M7522", "5303914400F9211", "9273338290F4010"]
.
We need to count passengers older than 60 years.
Step 1: Process first passenger "7868190130M7522"
- Extract age using slice
[11:13]
: "75" - Convert to integer: 75
- Check if 75 > 60: True
- Running count: 1
Step 2: Process second passenger "5303914400F9211"
- Extract age using slice
[11:13]
: "92" - Convert to integer: 92
- Check if 92 > 60: True
- Running count: 2
Step 3: Process third passenger "9273338290F4010"
- Extract age using slice
[11:13]
: "40" - Convert to integer: 40
- Check if 40 > 60: False
- Running count: 2
The generator expression (int(x[11:13]) > 60 for x in details)
produces the sequence: True, True, False
.
When passed to sum()
, this becomes: sum([True, True, False])
= sum([1, 1, 0])
= 2.
Therefore, the answer is 2 passengers are strictly older than 60.
Solution Implementation
1class Solution:
2 def countSeniors(self, details: List[str]) -> int:
3 """
4 Count the number of senior passengers (age > 60) from passenger details.
5
6 Each detail string contains passenger information where:
7 - Characters at index 11-12 represent the age (2 digits)
8
9 Args:
10 details: List of strings containing passenger information
11
12 Returns:
13 Number of passengers older than 60
14 """
15 # Extract age from positions 11-12 and count those greater than 60
16 # Using generator expression with sum() for efficient counting
17 senior_count = sum(int(detail[11:13]) > 60 for detail in details)
18
19 return senior_count
20
1class Solution {
2 /**
3 * Counts the number of seniors (age > 60) from an array of passenger details.
4 * Each detail string contains passenger information where age is located at indices 11-12.
5 *
6 * @param details Array of passenger detail strings
7 * @return Number of passengers older than 60
8 */
9 public int countSeniors(String[] details) {
10 int seniorCount = 0;
11
12 // Iterate through each passenger detail string
13 for (String passengerDetail : details) {
14 // Extract age from indices 11-12 (substring is exclusive at end index)
15 int age = Integer.parseInt(passengerDetail.substring(11, 13));
16
17 // Check if passenger is a senior (older than 60)
18 if (age > 60) {
19 seniorCount++;
20 }
21 }
22
23 return seniorCount;
24 }
25}
26
1class Solution {
2public:
3 int countSeniors(vector<string>& details) {
4 int seniorCount = 0;
5
6 // Iterate through each passenger detail string
7 for (const auto& passengerDetail : details) {
8 // Extract age from the string (characters at index 11 and 12)
9 // The age is always at positions 11-12 in the passenger detail string
10 int age = stoi(passengerDetail.substr(11, 2));
11
12 // Increment counter if the person is a senior (age > 60)
13 seniorCount += (age > 60);
14 }
15
16 return seniorCount;
17 }
18};
19
1/**
2 * Counts the number of senior citizens (age > 60) from passenger details
3 * @param details - Array of passenger detail strings where characters 11-12 represent age
4 * @returns Number of passengers older than 60
5 */
6function countSeniors(details: string[]): number {
7 // Filter passengers whose age (extracted from positions 11-12) exceeds 60
8 // The unary plus (+) converts the extracted substring to a number
9 return details.filter((passengerDetail: string) => {
10 const age: number = Number(passengerDetail.slice(11, 13));
11 return age > 60;
12 }).length;
13}
14
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the details
list. This is because the code iterates through each element in the list exactly once using a generator expression within the sum()
function. For each element, it performs a constant-time operation of string slicing (x[11:13]
) and integer comparison (> 60
).
The space complexity is O(1)
. The generator expression used in sum()
doesn't create an intermediate list but instead yields values one at a time, consuming constant extra space. The only additional space used is for the counter variable maintained by the sum()
function, which remains constant regardless of the input size.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Incorrect String Slicing Indices
One of the most common mistakes is using the wrong indices when extracting the age substring. Since Python uses 0-based indexing, the 12th and 13th characters are at indices 11 and 12, requiring the slice [11:13]
(not [12:14]
or [11:12]
).
Wrong Implementation:
# Incorrect: Only gets one character
age = int(detail[11:12]) # Gets only "6" from "65"
# Incorrect: Wrong position
age = int(detail[12:14]) # Gets "5A" which causes ValueError
Correct Implementation:
age = int(detail[11:13]) # Correctly gets "65"
2. Not Handling Edge Cases in Input Validation
The code assumes all input strings are valid and exactly 15 characters long. In production code, you might encounter malformed data.
Defensive Implementation:
def countSeniors(self, details: List[str]) -> int:
count = 0
for detail in details:
# Validate string length
if len(detail) != 15:
continue
# Validate age characters are digits
age_str = detail[11:13]
if not age_str.isdigit():
continue
if int(age_str) > 60:
count += 1
return count
3. Using >= Instead of > for Age Comparison
The problem specifically asks for passengers "strictly more than 60 years old", meaning age > 60, not age >= 60. A 60-year-old passenger should NOT be counted.
Wrong:
sum(int(detail[11:13]) >= 60 for detail in details) # Includes 60-year-olds
Correct:
sum(int(detail[11:13]) > 60 for detail in details) # Excludes 60-year-olds
4. Inefficient String Concatenation or Conversion
Some might try to extract characters individually and concatenate them, which is less efficient.
Inefficient Approach:
age = int(detail[11] + detail[12]) # String concatenation is unnecessary
Better Approach:
age = int(detail[11:13]) # Direct slicing is cleaner and faster
5. Memory-Inefficient Alternative Solutions
Creating intermediate lists when not necessary wastes memory.
Memory-Inefficient:
ages = [int(detail[11:13]) for detail in details] # Creates full list
return sum(1 for age in ages if age > 60)
Memory-Efficient (Original Solution):
return sum(int(detail[11:13]) > 60 for detail in details) # Generator expression
How many times is a tree node visited in a depth first search?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!