Phone Number Prefix - Problem
Phone Number Prefix Detection
Imagine you're building a phone directory system that needs to ensure data integrity. You've been given an array of
Your task is to determine if the phone directory is valid - meaning no phone number is a prefix of any other phone number. A string A is a prefix of string B if B starts with A.
Return
Examples:
•
•
•
Imagine you're building a phone directory system that needs to ensure data integrity. You've been given an array of
numbers representing phone numbers as strings.Your task is to determine if the phone directory is valid - meaning no phone number is a prefix of any other phone number. A string A is a prefix of string B if B starts with A.
Return
true if no phone number is a prefix of another; otherwise, return false.Examples:
•
["911", "91123", "456"] → false ("911" is a prefix of "91123")•
["123", "456", "789"] → true (no prefixes found)•
["12", "345", "1234"] → false ("12" is a prefix of "1234") Input & Output
example_1.py — Python
$
Input:
["911", "91123", "456"]
›
Output:
false
💡 Note:
The number "911" is a prefix of "91123", so the function returns false. When someone dials "911", the system cannot determine if they want to reach emergency services or continue dialing to "91123".
example_2.py — Python
$
Input:
["123", "456", "789"]
›
Output:
true
💡 Note:
No phone number in this array is a prefix of any other number. Each number is completely independent, so the function returns true.
example_3.py — Python
$
Input:
["12", "345", "1234", "567"]
›
Output:
false
💡 Note:
The number "12" is a prefix of "1234". Even though other numbers like "345" and "567" don't create conflicts, the existence of one prefix relationship is enough to return false.
Visualization
Tap to expand
Understanding the Visualization
1
Receive Phone List
Start with an unsorted list of phone numbers that need validation
2
Sort Numbers
Arrange numbers lexicographically so potential prefixes appear adjacent
3
Check Adjacents
Compare each number only with its immediate neighbor for prefix relationship
4
Detect Conflicts
If any number is a prefix of the next, return false immediately
Key Takeaway
🎯 Key Insight: Sorting transforms an O(n²) comparison problem into an O(n) adjacent-check problem, dramatically improving efficiency!
Time & Space Complexity
Time Complexity
O(n × m)
n numbers, each with average length m for trie operations
✓ Linear Growth
Space Complexity
O(n × m)
Trie storage requires space proportional to total characters
⚡ Linearithmic Space
Constraints
- 1 ≤ numbers.length ≤ 104
- 1 ≤ numbers[i].length ≤ 10
- numbers[i] consists of digits only
- All phone numbers are unique
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code