Sponsored
Sponsored
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.
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.
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 C# solution collects the age part using Substring
and converts it to an integer with int.Parse
. It counts the number of entries with ages over 60.
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.
The time complexity is O(n)
due to single traversal through details. The space complexity remains O(1)
.
1def count_senior_citizens(details):
2 senior_count = 0
3 for detail in details:
4 age = (int(detail[11]) * 10) + int(detail[12])
5 if age > 60:
6 senior_count += 1
7 return senior_count
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.