Number of Senior Citizens
EasyPrompt
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.
Approaches
2 approaches with complexity analysis and trade-offs.
This straightforward approach iterates through each passenger's detail string. For each string, it extracts the age portion using the substring method. This extracted string is then converted to an integer using Integer.parseInt(). Finally, it checks if the age is greater than 60 and increments a counter if it is.
Algorithm
- Initialize a counter
seniorCountto 0. - For each
detailstring in thedetailsarray:- Extract the age string using
detail.substring(11, 13). - Convert the age string to an integer
age. - If
age > 60, incrementseniorCount.
- Extract the age string using
- Return
seniorCount.
Walkthrough
The algorithm is simple:
- Initialize a counter for senior citizens,
seniorCount, to 0. - Loop through every
detailstring in the input arraydetails. - Inside the loop, for the current
detail, isolate the age information. The age is a two-digit number located at indices 11 and 12. We can extract this usingdetail.substring(11, 13). - The result of the substring operation is a
String(e.g.,"75"). This needs to be converted to a number for comparison. TheInteger.parseInt()method is used for this conversion. - An
ifcondition checks if the parsed age is strictly greater than 60. - If the condition is true,
seniorCountis incremented. - After the loop has processed all the strings, the final
seniorCountis returned.
class Solution { public int countSeniors(String[] details) { int seniorCount = 0; for (String detail : details) { // Extract the age substring from index 11 up to (but not including) 13. String ageString = detail.substring(11, 13); // Convert the age string to an integer. int age = Integer.parseInt(ageString); // If the passenger is older than 60, increment the count. if (age > 60) { seniorCount++; } } return seniorCount; }}Complexity
Time
O(N), where N is the number of passengers (the length of the `details` array). We perform a single pass through the array. The operations inside the loop (`substring`, `parseInt`) are constant time because the input string format is fixed.
Space
O(1). The extra space used is constant, regardless of the input size. We only need a counter and a temporary string variable within the loop's scope.
Trade-offs
Pros
Highly readable and easy to understand.
Directly translates the problem statement into code.
Cons
Incurs a small performance overhead from creating a new substring object and calling the
Integer.parseInt()method for each passenger. While negligible for the given constraints, it's technically less efficient than direct character manipulation.
This approach improves upon the first by avoiding the creation of intermediate strings and the overhead of the parseInt method. It directly accesses the characters representing the age at their specific indices and calculates the numerical age value using basic arithmetic. This is a more performant way to achieve the same result.
Algorithm
- Initialize a counter
seniorCountto 0. - For each
detailstring in thedetailsarray:- Get the tens digit character:
char tens = detail.charAt(11). - Get the units digit character:
char units = detail.charAt(12). - Calculate the integer age:
int age = (tens - '0') * 10 + (units - '0'). - If
age > 60, incrementseniorCount.
- Get the tens digit character:
- Return
seniorCount.
Walkthrough
This method also involves a single loop through the details array but optimizes how the age is determined.
- Initialize a counter
seniorCountto 0. - Iterate through each
detailstring. - For the current
detail, we access the character at index 11 (the tens digit of the age) and the character at index 12 (the units digit). - To convert a digit character to its integer value, we can subtract the ASCII value of '0'. For example,
'7' - '0'results in the integer7. - The full age is calculated by combining the two digits:
age = (tens_digit_char - '0') * 10 + (units_digit_char - '0'). - This calculated integer
ageis then checked if it's greater than 60. - If it is,
seniorCountis incremented. - After the loop, the total
seniorCountis returned. This avoids object allocation and method calls inside the loop, making it faster.
class Solution { public int countSeniors(String[] details) { int seniorCount = 0; for (String detail : details) { // Get the character for the tens digit (index 11) char tensDigit = detail.charAt(11); // Get the character for the units digit (index 12) char unitsDigit = detail.charAt(12); // Calculate the age using character arithmetic int age = (tensDigit - '0') * 10 + (unitsDigit - '0'); // If the passenger is older than 60, increment the count. if (age > 60) { seniorCount++; } } return seniorCount; }}Complexity
Time
O(N), where N is the length of the `details` array. We iterate through the array once, and all operations inside the loop (character access, arithmetic) are constant time.
Space
O(1). The space used is constant as we only need a counter and a few primitive variables. No new objects are created in the loop, making it very memory-efficient.
Trade-offs
Pros
Most efficient solution in terms of both time and memory due to minimal overhead.
Avoids creating temporary objects, reducing pressure on the garbage collector.
Cons
The code for calculating the age via character arithmetic might be slightly less self-explanatory to a developer unfamiliar with the technique compared to the
parseIntmethod.
Solutions
Solution
class Solution {public int countSeniors(String[] details) { int ans = 0; for (var x : details) { int age = Integer.parseInt(x.substring(11, 13)); if (age > 60) { ++ans; } } return ans; }}class Solution {public: int countSeniors(vector<string> &details) { int ans = 0; for (auto &x : details) { int age = stoi(x.substr(11, 2)); ans += age > 60; } return ans; }};class Solution: def countSeniors( self, details: List[str]) -> int: return sum(int(x[11: 13]) > 60 for x in details)Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.