# Number of Senior Citizens
**Difficulty:** EASY
[External](https://leetcode.com/problems/number-of-senior-citizens)
Canonical: https://scaleengineer.com/dsa/problems/number-of-senior-citizens
**Data structures:** Array, String
---
## Problem
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**._

**Example 1:**

**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.

**Example 2:**

**Input:** details = ["1313579440F2036","2921522980M5644"]
**Output:** 0
**Explanation:** None of the passengers are older than 60.

**Constraints:**

* `1 <= details.length <= 100`
* `details[i].length == 15`
* `details[i] consists of digits from '0' to '9'.`
* `details[i][10] is either 'M' or 'F' or 'O'.`
* The phone numbers and seat numbers of the passengers are distinct.

# Approaches
## Iterative Approach with Substring and Parsing
This straightforward approach iterates through each passenger's detail string. For each string, it extracts the age portion using the `substring` method. This extracted string is then converted to an integer using `Integer.parseInt()`. Finally, it checks if the age is greater than 60 and increments a counter if it is.
**Time:** O(N), where N is the number of passengers (the length of the `details` array). We perform a single pass through the array. The operations inside the loop (`substring`, `parseInt`) are constant time because the input string format is fixed. · **Space:** O(1). The extra space used is constant, regardless of the input size. We only need a counter and a temporary string variable within the loop's scope.
**Pros:** Highly readable and easy to understand.; Directly translates the problem statement into code.
**Cons:** Incurs a small performance overhead from creating a new substring object and calling the `Integer.parseInt()` method for each passenger. While negligible for the given constraints, it's technically less efficient than direct character manipulation.
### Explanation
The algorithm is simple:
1.  Initialize a counter for senior citizens, `seniorCount`, to 0.
2.  Loop through every `detail` string in the input array `details`.
3.  Inside the loop, for the current `detail`, isolate the age information. The age is a two-digit number located at indices 11 and 12. We can extract this using `detail.substring(11, 13)`.
4.  The result of the substring operation is a `String` (e.g., `"75"`). This needs to be converted to a number for comparison. The `Integer.parseInt()` method is used for this conversion.
5.  An `if` condition checks if the parsed age is strictly greater than 60.
6.  If the condition is true, `seniorCount` is incremented.
7.  After the loop has processed all the strings, the final `seniorCount` is returned.

```java
class Solution {
    public int countSeniors(String[] details) {
        int seniorCount = 0;
        for (String detail : details) {
            // Extract the age substring from index 11 up to (but not including) 13.
            String ageString = detail.substring(11, 13);
            // Convert the age string to an integer.
            int age = Integer.parseInt(ageString);
            // If the passenger is older than 60, increment the count.
            if (age > 60) {
                seniorCount++;
            }
        }
        return seniorCount;
    }
}
```
### Algorithm
- Initialize a counter `seniorCount` to 0.
- For each `detail` string in the `details` array:
  - Extract the age string using `detail.substring(11, 13)`.
  - Convert the age string to an integer `age`.
  - If `age > 60`, increment `seniorCount`.
- Return `seniorCount`.

## Optimized Iteration with Character Arithmetic
This approach improves upon the first by avoiding the creation of intermediate strings and the overhead of the `parseInt` method. It directly accesses the characters representing the age at their specific indices and calculates the numerical age value using basic arithmetic. This is a more performant way to achieve the same result.
**Time:** O(N), where N is the length of the `details` array. We iterate through the array once, and all operations inside the loop (character access, arithmetic) are constant time. · **Space:** O(1). The space used is constant as we only need a counter and a few primitive variables. No new objects are created in the loop, making it very memory-efficient.
**Pros:** Most efficient solution in terms of both time and memory due to minimal overhead.; Avoids creating temporary objects, reducing pressure on the garbage collector.
**Cons:** The code for calculating the age via character arithmetic might be slightly less self-explanatory to a developer unfamiliar with the technique compared to the `parseInt` method.
### Explanation
This method also involves a single loop through the `details` array but optimizes how the age is determined.
1.  Initialize a counter `seniorCount` to 0.
2.  Iterate through each `detail` string.
3.  For the current `detail`, we access the character at index 11 (the tens digit of the age) and the character at index 12 (the units digit).
4.  To convert a digit character to its integer value, we can subtract the ASCII value of '0'. For example, `'7' - '0'` results in the integer `7`.
5.  The full age is calculated by combining the two digits: `age = (tens_digit_char - '0') * 10 + (units_digit_char - '0')`.
6.  This calculated integer `age` is then checked if it's greater than 60.
7.  If it is, `seniorCount` is incremented.
8.  After the loop, the total `seniorCount` is returned. This avoids object allocation and method calls inside the loop, making it faster.

```java
class Solution {
    public int countSeniors(String[] details) {
        int seniorCount = 0;
        for (String detail : details) {
            // Get the character for the tens digit (index 11)
            char tensDigit = detail.charAt(11);
            // Get the character for the units digit (index 12)
            char unitsDigit = detail.charAt(12);
            
            // Calculate the age using character arithmetic
            int age = (tensDigit - '0') * 10 + (unitsDigit - '0');
            
            // If the passenger is older than 60, increment the count.
            if (age > 60) {
                seniorCount++;
            }
        }
        return seniorCount;
    }
}
```
### Algorithm
- Initialize a counter `seniorCount` to 0.
- For each `detail` string in the `details` array:
  - Get the tens digit character: `char tens = detail.charAt(11)`.
  - Get the units digit character: `char units = detail.charAt(12)`.
  - Calculate the integer age: `int age = (tens - '0') * 10 + (units - '0')`.
  - If `age > 60`, increment `seniorCount`.
- Return `seniorCount`.

# Solutions
### Java

```java
class Solution {
public
  int countSeniors(String[] details) {
    int ans = 0;
    for (var x : details) {
      int age = Integer.parseInt(x.substring(11, 13));
      if (age > 60) {
        ++ans;
      }
    }
    return ans;
  }
}

```

### CPP

```cpp
class Solution {
public:
  int countSeniors(vector<string> &details) {
    int ans = 0;
    for (auto &x : details) {
      int age = stoi(x.substr(11, 2));
      ans += age > 60;
    }
    return ans;
  }
};

```

### Python

```python
class Solution:
    def countSeniors(
        self, details: List[str]) -> int: return sum(int(x[11: 13]) > 60 for x in details)

```
