#193
Valid Phone Numbers
EasyShellRegular ExpressionsString Matching
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using regex patterns allows us to efficiently check for valid phone numbers in a single pass, making this approach much faster and more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Read the entire file content at once.
- 2Step 2: Use a single regex pattern to match both valid formats in one go.
- 3Step 3: Print all matched phone numbers.
solution.py6 lines
1import re
2with open('file.txt') as f:
3 content = f.read()
4 matches = re.findall(r'\(\d{3}\) \d{3}-\d{4}|\d{3}-\d{3}-\d{4}', content)
5 for match in matches:
6 print(match)ℹ
Complexity note: This is O(n) because we read the file once and apply regex matching, which is linear with respect to the input size.
- 1Using regex can simplify the matching process significantly.
- 2Reading the entire file at once can be more efficient than line-by-line processing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.