Find number of distinct years in a paragraph
Filed under Paytm
Free read 2 of 3Use a regular expression pattern like '\d{2}-\d{2}-(\d{4})' to capture all date occurrences.
The question
Given a paragraph string, extract all dates formatted as 'dd-mm-yyyy' and return the count of unique years found.
Constraints
- Input string length up to 10^5 characters.
- Dates are strictly formatted as dd-mm-yyyy.
- Years are the last 4 digits of the date string.
Examples
- Input
- Events on 12-05-2020 and 15-06-2020.
- Output
- 1
- Why
- Both dates share the year 2020.
Approach
Use a regular expression pattern like '\d{2}-\d{2}-(\d{4})' to capture all date occurrences.
Iterate through all matches, extract the year group, and add it to a hash set.
Return the size of the set as the final count of distinct years.
Solution
O(N) time, O(K) space where K is number of unique years
import re
def count_unique_years(text):
years = re.findall(r'\d{2}-\d{2}-(\d{4})', text)
return len(set(years))
# Tests
assert count_unique_years('12-05-2020, 15-06-2021') == 2
assert count_unique_years('No dates here') == 0
assert count_unique_years('10-10-2020, 11-11-2020') == 1
Tips
- What they are testing: Ensure the regex correctly handles dates at the start/end of strings or adjacent to punctuation.
- Common mistake: Using a simple split by space, which fails if a date is followed by a period or comma.
Related Paytm questions
Collected from public candidate posts and coding forums. Updated Nov 2026.