Leetcode 2678. Number of Senior Citizens
You are given a list of strings, where each string represents a person’s age (from 0 to 120 years). Write a function to count the number of senior citizens in the list. A senior citizen is defined as someone who is 60 years old or older.
Input: ["22", "18", "77", "60", "91"]
Output: 3
Here’s the implementation of the strategy.
import java.util.List;
public class SeniorCitizensCounter {
public int countSeniorCitizens(List<String> ages) {
int count = 0;
for (String ageStr : ages) {
int age = Integer.parseInt(ageStr);
if (age >= 60) {
count += 1;
}
}
return count;
}
public static void main(String[] args) {
SeniorCitizensCounter counter = new SeniorCitizensCounter();
List<String> ages = List.of("22", "18", "77", "60", "91");
int result = counter.countSeniorCitizens(ages);
System.out.println("Number of senior citizens: " + result); // Output: 3
}
}
The time complexity of this solution is O(n), where n
is the number of elements in the input list. This is because we need to iterate over each element once to check the age and update the count if the age is a senior citizen’s age.
Overall, this should efficiently solve the problem within the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?