algoadvance

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

  1. What data structure holds the ages?
    • A vector of integers representing the ages.
  2. 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.
  3. Is the vector always non-empty, or do we need to handle empty input too?
    • We need to handle empty input gracefully.

Strategy

  1. Initialize a Counter: Start with a counter set to 0.
  2. Iterate through the Ages: For each age in the vector, check if it is greater than or equal to 65.
  3. Increment the Counter: If the age is 65 or older, increment the counter.
  4. 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

  1. Function Definition: The function countSeniorCitizens takes a constant reference to a std::vector<int> which holds the ages.
  2. Initialize Counter: We initialize an integer seniorCount to 0.
  3. Loop through Ages: We use a range-based for loop to iterate through each age in the vector.
  4. Increment if Condition Met: If the current age is 65 or more, we increment seniorCount.
  5. Return the Result: After the loop, we return the value of seniorCount.

Time Complexity

This straightforward approach ensures efficient counting with minimal overhead.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI