Phone Number Prefix Problem
#3491
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3491.
You are given a string array numbers that represents phone numbers. Return true if no phone number is a prefix of any other phone number; otherwise, return false.
Example 1:
Input: numbers = ["1","2","4","3"]
Output: true
Explanation:
No number is a prefix of another number, so the output is true.
Example 2:
Input: numbers = ["001","007","15","00153"]
Output: false
Explanation:
The string "001" is a prefix of the string "00153". Thus, the output is false.
Constraints:
2 <= numbers.length <= 501 <= numbers[i].length <= 50- All numbers contain only digits
'0'to'9'.
Solution
Approach: Sort by Length, Then Compare
If a is a prefix of b, then a is not longer than b. Sort the numbers by length, so every possible prefix of a number comes before it. Then, for each number, check whether any earlier number is a prefix of it. If one is, return false. If no check succeeds, return true.
Two identical numbers count as well: each one is a prefix of the other.
Complexity: O(n2 * m + n log n) time and O(1) extra space besides the sort, where n is the count of numbers and m their length.
class Solution:
def phonePrefix(self, numbers: List[str]) -> bool:
numbers.sort(key=len)
for i, s in enumerate(numbers):
if any(s.startswith(t) for t in numbers[:i]):
return False
return True