#2678
Number of Senior Citizens
EasyArrayStringArrayString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is similar to the brute force approach but focuses on efficiency by directly extracting and calculating the age in a single pass through the array, maintaining the same time complexity but ensuring clarity.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a counter to zero.
- 2Step 2: Loop through each passenger's details in the array.
- 3Step 3: For each passenger, extract the age from the string using the characters at index 11 and 12.
- 4Step 4: Convert the extracted characters to an integer to get the age.
- 5Step 5: If the age is greater than 60, increment the counter.
- 6Step 6: Return the counter.
solution.py7 lines
1def countSeniorCitizens(details):
2 count = 0
3 for detail in details:
4 age = int(detail[11]) * 10 + int(detail[12])
5 if age > 60:
6 count += 1
7 return countℹ
Complexity note: The time complexity remains O(n) as we traverse the list once. The space complexity is O(1) since we only use a single counter variable.
- 1Extracting age from a fixed position in a string is a common pattern.
- 2Understanding how to convert characters to integers is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.