Number of Senior Citizens solution and explanation
9 more videos on this problem
Number of Senior Citizens - Leetcode 2678 - PythonNeetCodeIO · 5:07 · 6K views
Leetcode 2678 Number of Senior CitizensAlgorithmicIQ · 10:08 · 1K views
Leetcode | 2678. Number of Senior Citizens | Easy | Java SolutionDeveloper Docs · 3:21 · 527 views
“LeetCode 2678 – Number of Senior Citizens | Java Solution Explained Simply!”Recurso · 9:33 · 418 views
2678. Number of Senior Citizens (Leetcode Easy)Programming Live with Larry · 2:57 · 344 views
2678 Number of Senior Citizens. #leetcode #2678 #1augustWitchy · 9:12 · 111 views
2678. Number of Senior Citizens | LeetCode | TUTORIAL - 53 | DSA PLAYLISTCoding Kart · 5:07 · 83 views
Leetcode 2678. | Number of Senior Citizens | Easy Problem ExplainedExperimental Coder · 9:10 · 63 views
Leetcode - 2678 - Number of Senior Citizens - TypeScript/ JavaScriptcoding BBQ · 3:53 · 63 views
LeetCode: 2678.Number of Senior Citizens | Day 1CodeWithMaaz · 7:48 · 62 views
The problem
You are given a 0-indexed array of strings details. Each element of details provides information about a given passenger compressed into a string of length 15. The system is such that:
- The first ten characters consist of the phone number of passengers.
- The next character denotes the gender of the person.
- The following two characters are used to indicate the age of the person.
- The last two characters determine the seat allotted to that person.
Return the number of passengers who are strictly more than 60 years old.
Example 1:
Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"] Output: 2 Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old.
Example 2:
Input: details = ["1313579440F2036","2921522980M5644"] Output: 0 Explanation: None of the passengers are older than 60.
Constraints:
1 <= details.length <= 100details[i].length == 15details[i] consists of digits from '0' to '9'.details[i][10] is either 'M' or 'F' or 'O'.- The phone numbers and seat numbers of the passengers are distinct.
Approach overview
Problem Overview: Each passenger record is a 15‑character string containing phone number, gender, age, and seat number. The age appears at positions 11 and 12. You need to scan the array of records and count how many passengers are older than 60.
Approach 1: String Substring Extraction (O(n) time, O(1) space)
Iterate through the input array and extract the age portion of each record using a substring operation. Since the age is stored in characters s[11:13], convert that substring into an integer and check whether it is greater than 60. If it is, increment a counter. This approach relies on standard string slicing and integer parsing, which keeps the implementation clean and easy to read. Time complexity is O(n) because you scan each record once, and space complexity is O(1) since only a few variables are used.
This method works well when readability matters and you want straightforward string handling. It uses basic operations from string processing and simple iteration over an array. Most developers reach for this version first because the intent is obvious: extract the age substring and compare it.
Approach 2: Character-Based Calculation (O(n) time, O(1) space)
Instead of creating a substring, compute the age directly from the characters. The tens digit is at s[11] and the ones digit at s[12]. Convert them to numbers and compute age = (s[11] - '0') * 10 + (s[12] - '0'). Then check whether the computed age is greater than 60. This avoids substring allocation and integer parsing.
The key insight is that the data format is fixed length, so you can access the age digits directly. That makes the solution slightly more efficient in practice while keeping the same asymptotic complexity: O(n) time for scanning the records and O(1) extra space. This technique shows up often in problems involving encoded strings or fixed‑format records.
Recommended for interviews: Both approaches pass easily because the problem is mostly about recognizing the fixed position of the age field. Start with substring extraction to demonstrate understanding of the format. The character‑based calculation shows stronger attention to detail and avoids extra parsing work, which interviewers often appreciate when discussing optimization in string manipulation tasks.
Approach 1: String Substring Extraction
Approach: Extract the age from each detail string by selecting the appropriate substring. Convert this substring to an integer and count how many such integers are greater than 60.
The given details string has a fixed format. We know from the problem description that the age of the person is stored between the 11th and 12th character indices. By iterating over each string, extracting these characters, converting them to a number, and then checking if the number is greater than 60, we can count the number of senior citizens.
def count_senior_citizens(details):
senior_count = 0
for detail in details:
age = int(detail[11:13])
if age > 60:
senior_count += 1
return senior_countimport java.util.List;
public class Main {
public static int countSeniorCitizens(List<String> details) {
int seniorCount = 0;
for (String detail : details) {
int age = Integer.parseInt(detail.substring(11, 13));
if (age > 60) {
seniorCount++;
}
}
return seniorCount;
}
}#include <iostream>
#include <string>
using namespace std;
int countSeniorCitizens(const vector<string>& details) {
int seniorCount = 0;
for (const auto &detail : details) {
int age = stoi(detail.substr(11,2));
if (age > 60) {
++seniorCount;
}
}
return seniorCount;
}function countSeniorCitizens(details) {
let seniorCount = 0;
for (const detail of details) {
const age = parseInt(detail.substring(11, 13), 10);
if (age > 60) {
seniorCount++;
}
}
return seniorCount;
}#include <stdio.h>
#include <stdlib.h>
int countSeniorCitizens(char details[][16], int size) {
int seniorCount = 0;
for (int i = 0; i < size; ++i) {
int age = (details[i][11] - '0') * 10 + (details[i][12] - '0');
if (age > 60) {
++seniorCount;
}
}
return seniorCount;
}using System;
using System.Collections.Generic;
public class Solution {
public int CountSeniorCitizens(List<string> details) {
int seniorCount = 0;
foreach (string detail in details) {
int age = int.Parse(detail.Substring(11, 2));
if (age > 60) {
seniorCount++;
}
}
return seniorCount;
}
}This function iterates through each string in the list, extracts the age substring (at indices 11 to 12), converts it to an integer, and checks if it is greater than 60. If so, it increments the counter senior_count.
The time complexity is O(n) where n is the number of entries in details.
The space complexity is O(1) as we are using a fixed amount of additional space.
Approach 2: Character-Based Calculation
Approach: Instead of using string slicing or substrings, calculate the age by examining the individual characters and converting them into the age. This approach does not explicitly create a substring but directly works with character indices and mathematical operations.
This avoids the creation of additional strings and might be beneficial in languages where string manipulation is costly.
def count_senior_citizens(details):
senior_count = 0
for detail in details:
age = (int(detail[11]) * 10) + int(detail[12])
if age > 60:
senior_count += 1
return senior_countpublic class Main {
public static int countSeniorCitizens(List<String> details) {
int seniorCount = 0;
for (String detail : details) {
int age = (detail.charAt(11) - '0') * 10 + (detail.charAt(12) - '0');
if (age > 60) {
seniorCount++;
}
}
return seniorCount;
}
}#include <vector>
#include <string>
using namespace std;
int countSeniorCitizens(const vector<string>& details) {
int seniorCount = 0;
for (const auto &detail : details) {
int age = (detail[11] - '0') * 10 + (detail[12] - '0');
if (age > 60) {
++seniorCount;
}
}
return seniorCount;
}function countSeniorCitizens(details) {
let seniorCount = 0;
for (const detail of details) {
const age = (parseInt(detail[11]) * 10) + parseInt(detail[12]);
if (age > 60) {
seniorCount++;
}
}
return seniorCount;
}#include <stdio.h>
int countSeniorCitizens(char details[][16], int size) {
int seniorCount = 0;
for (int i = 0; i < size; ++i) {
int age = (details[i][11] - '0') * 10 + (details[i][12] - '0');
if (age > 60) {
++seniorCount;
}
}
return seniorCount;
}using System;
using System.Collections.Generic;
public class Solution {
public int CountSeniorCitizens(List<string> details) {
int seniorCount = 0;
foreach (string detail in details) {
int age = (detail[11] - '0') * 10 + (detail[12] - '0');
if (age > 60) {
seniorCount++;
}
}
return seniorCount;
}
}Here, we manually form the age by converting both age characters at indices 11 and 12 to integers and then calculating the age. We increment senior_count if the calculated age is greater than 60.
The time complexity is O(n) due to single traversal through details. The space complexity remains O(1).
Approach 3: Traversal and Counting
We can traverse each string x in details and convert the 12th and 13th characters (indexed at 11 and 12) of x to integers, and check if they are greater than 60. If so, we add one to the answer.
After the traversal, we return the answer.
The time complexity is O(n), where n is the length of details. The space complexity is $O(1)`.
function countSeniors(details: string[]): number {
return details.filter(x => +x.slice(11, 13) > 60).length;
}func countSeniors(details []string) (ans int) {
for _, x := range details {
age, _ := strconv.Atoi(x[11:13])
if age > 60 {
ans++
}
}
return
}impl Solution {
pub fn count_seniors(details: Vec<String>) -> i32 {
details
.iter()
.filter_map(|s| s[11..13].parse::<i32>().ok())
.filter(|&age| age > 60)
.count() as i32
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| String Substring Extraction | The time complexity is |
| Character-Based Calculation | The time complexity is |
| Traversal and Counting | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String Substring Extraction | O(n) | O(1) | Best for readability and quick implementation using built-in substring and integer parsing. |
| Character-Based Calculation | O(n) | O(1) | Preferred when avoiding substring creation or parsing overhead in fixed-format strings. |
Frequently asked questions
Is Number of Senior Citizens easy or hard?
Number of Senior Citizens is classified as an Easy problem on LeetCode with a high acceptance rate above 80%. The main challenge is recognizing the fixed string format and correctly extracting the age field.
Number of Senior Citizens Python/Java solution
Both Python and Java implementations follow the same logic: read characters at index 11 and 12, compute the age, and count values greater than 60. Python often uses slicing like s[11:13], while Java typically uses char access and arithmetic to compute the age.
How to solve Number of Senior Citizens in O(n)?
Iterate through the array of passenger detail strings and read the age stored at positions 11 and 12. Convert those characters into an integer and check if the value is greater than 60. Increment a counter for each qualifying record, resulting in a single-pass O(n) solution.
What is the best approach for Number of Senior Citizens?
The character-based calculation approach is typically the best. It directly reads the two age digits from indices 11 and 12 and computes the number without creating a substring. This keeps the solution O(n) time and O(1) space while avoiding extra parsing work.
Is Number of Senior Citizens asked at Google/Amazon/Meta?
Problems of this style appear frequently in screening rounds at large tech companies. While this exact question is categorized as easy, similar fixed-format string parsing tasks are common in interviews at companies like Amazon and Google.
What data structure is used in Number of Senior Citizens?
The problem mainly uses arrays and strings. The input is an array of encoded passenger strings, and the solution involves iterating through the array and extracting characters from each string.
What is the time complexity of Number of Senior Citizens?
The time complexity is O(n), where n is the number of passenger records. Each record is scanned once to read the age digits and compare them with 60. Space complexity remains O(1) because only a counter and a few temporary variables are used.
