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.
For Java, we use the substring
method to cut out the age part and Integer.parseInt
to transform it into an integer. If the age is more than 60, it updates the seniorCount
.
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 <stdio.h>
2
3int countSeniorCitizens(char details[][16], int size) {
4 int seniorCount = 0;
5 for (int i = 0; i < size; ++i) {
6 int age = (details[i][11] - '0') * 10 + (details[i][12] - '0');
7 if (age > 60) {
8 ++seniorCount;
9 }
10 }
11 return seniorCount;
12}
Directly computes the age from characters at the 11th and 12th positions by subtracting '0' from them, multiplying the first by 10, and adding to get the integer age value.