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.
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
.
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)
.
1#include <vector>
2#include <string>
3using namespace std;
4
5int countSeniorCitizens(const vector<string>& details) {
6 int seniorCount = 0;
7 for (const auto &detail : details) {
8 int age = (detail[11] - '0') * 10 + (detail[12] - '0');
9 if (age > 60) {
10 ++seniorCount;
11 }
12 }
13 return seniorCount;
14}
Applies character arithmetic to fetch the ages directly from the character array, calculates the age, and counts those greater than 60.