algoadvance

Leetcode 2678. Number of Senior Citizens

Problem Statement

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.

Example

Input: ["22", "18", "77", "60", "91"]
Output: 3

Clarifying Questions

  1. Input Format: Are all the ages given in the form of strings, and are they all valid and within the range of 0 to 120?
    • Assumption: Yes.
  2. Edge Cases: What if the input list is empty?
    • Assumption: If the input list is empty, the count of senior citizens should be 0.
  3. Definition of Senior Citizen: Is the 60-year-old mark included in the definition of senior citizens?
    • Clarification: Yes, anyone aged 60 or older is a senior citizen.

Strategy

  1. Initialize a counter to keep track of the number of senior citizens.
  2. Loop through each string in the list: a. Convert the string to an integer. b. Check if the integer is greater than or equal to 60. c. If it is, increment the counter.
  3. Return the counter value after processing all the strings.

Here’s the implementation of the strategy.

Code

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
    }
}

Time Complexity

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.

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