Leetcode 2678 - Number of Senior Citizens

Author: Lee Zheng Jing

August 1, 2024

Problem Description

You are given a 0-indexed array of strings details. Each element of details provides information about a given passenger compressed into a string of length 15. The system is such that:

  • The first ten characters consist of the phone number of passengers.
  • The next character denotes the gender of the person.
  • The following two characters are used to indicate the age of the person.
  • The last two characters determine the seat allotted to that person.
  • Return the number of passengers who are strictly more than 60 years old.

Examples

Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"]

Output: 2

Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old.

Thought Process / Intuition

In order to count all the passengers with age greater than 60, we will have to iterate through the whole list. Afterwards, we have to extract the information from the 11th and 12th index of the string in order to get the age of the passenger and check it against 60. Then, we increment our counter of the passengers. An easy question to start off the August daily leetcode challenge.

Approach

  1. Initialize a counter variable to 0.
  2. Iterate through the list of strings.
  3. Extract the age of the passenger from the 11th and 12th index of the string.
  4. Check if the age is greater than 60.
  5. If it is, increment the counter.
  6. Return the counter.

Solution

class Solution:
    def countSeniors(self, details: List[str]) -> int:
        count = 0
        for detail in details:
            if int(detail[11:13]) > 60:
                count += 1
        return count
            

Complexity Analysis

Time complexity: O(n)O(n)

  • The time complexity of the solution is O(n)O(n).
  • The solution iterates through the list of strings, where nn is the number of strings in the list.
  • The solution extracts the age of the passenger from the 11th and 12th index of the string, which takes O(1)O(1) time.
  • Thus, the overall time complexity of the solution is O(n)O(n).

Space complexity: O(1)O(1)

  • The space complexity of the solution is O(1)O(1).
  • The solution uses a constant amount of extra space, regardless of the input size.