Leetcode 2678. Number of Senior Citizens
Problem Statement
Given a data structure that holds the ages of a group of people, write a function to return the number of senior citizens in the group. A senior citizen is defined as someone who is at least 65 years old.
Clarifying Questions
- What data structure holds the ages?
- A vector of integers representing the ages.
- Can the ages data structure contain invalid ages (e.g., negative numbers or numbers greater than something like 130)?
- This is an edge case we can consider. We’ll assume for now that all ages are valid integers within a reasonable range.
- Is the vector always non-empty, or do we need to handle empty input too?
- We need to handle empty input gracefully.
Strategy
- Initialize a Counter: Start with a counter set to 0.
- Iterate through the Ages: For each age in the vector, check if it is greater than or equal to 65.
- Increment the Counter: If the age is 65 or older, increment the counter.
- Return the Counter: Once all ages have been checked, return the counter.
Code
Here is the implementation of the solution in C++:
#include <vector>
int countSeniorCitizens(const std::vector<int>& ages) {
int seniorCount = 0;
for (int age : ages) {
if (age >= 65) {
seniorCount++;
}
}
return seniorCount;
}
Explanation
- Function Definition: The function
countSeniorCitizens takes a constant reference to a std::vector<int> which holds the ages.
- Initialize Counter: We initialize an integer
seniorCount to 0.
- Loop through Ages: We use a range-based for loop to iterate through each age in the vector.
- Increment if Condition Met: If the current age is 65 or more, we increment
seniorCount.
- Return the Result: After the loop, we return the value of
seniorCount.
Time Complexity
- Time Complexity: O(n), where n is the number of elements in the input vector. We need to iterate through each element once.
- Space Complexity: O(1), since we are only using a fixed amount of extra space (the integer
seniorCount).
This straightforward approach ensures efficient counting with minimal overhead.
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
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?