Number of Senior Citizens
Problem
You are given an array details of fixed-length strings. Each string has length 15 and encodes one passenger: characters 0..9 are the phone number, character 10 is the gender, characters 11..12 are the two-digit age, and characters 13..14 are the seat. Return how many passengers are strictly more than 60 years old.
details = ["7868190130M7522","5303914400F9211","9273338290F4010"]2def countSeniors(details):
count = 0
for d in details:
# characters at indices 11 and 12 form the age
age = int(d[11:13])
if age > 60:
count += 1
return count
function countSeniors(details) {
let count = 0;
for (const d of details) {
// characters at indices 11 and 12 form the age
const age = Number(d.slice(11, 13));
if (age > 60) {
count++;
}
}
return count;
}
int countSeniors(String[] details) {
int count = 0;
for (String d : details) {
// characters at indices 11 and 12 form the age
int age = Integer.parseInt(d.substring(11, 13));
if (age > 60) {
count++;
}
}
return count;
}
int countSeniors(vector<string>& details) {
int count = 0;
for (auto& d : details) {
// characters at indices 11 and 12 form the age
int age = stoi(d.substr(11, 2));
if (age > 60) {
count++;
}
}
return count;
}
Explanation
Every passenger record is a fixed 15-character string, so the meaning of each position never changes. We do not need to split on any delimiter — we just slice the right window out of each string.
The two characters at indices 11 and 12 are the tens digit and the units digit of the age. Reading them together as a number gives the age directly: in the hint's terms, age = d[11]*10 + d[12], which is exactly what int(d[11:13]) computes.
We keep a single running count. For each passenger we extract the age and test age > 60. The comparison is strict: someone who is exactly 60 does not count, only ages 61 and above do.
Because each string is examined once and the slice is a constant two characters, the whole pass is linear in the number of passengers and uses only the counter as extra space.
Example: for ["7868190130M7522","5303914400F9211","9273338290F4010"] the ages are 75, 92, and 40. The first two pass the > 60 test, the third does not, so the answer is 2.