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.
1def count_senior_citizens(details):
2 senior_count = 0
3 for detail in details:
4 age = int(detail[11:13])
5 if age > 60:
6 senior_count += 1
7 return senior_count
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)
.
1function countSeniorCitizens(details) {
2 let seniorCount = 0;
3 for (const detail of details) {
4 const age = (parseInt(detail[11]) * 10) + parseInt(detail[12]);
5 if (age > 60) {
6 seniorCount++;
7 }
8 }
9 return seniorCount;
10}
This JavaScript version directly accesses age characters by index, forms the age number, and increments seniorCount
if age is more than 60.