3491. Phone Number Prefix π
Description
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 <= 50
1 <= numbers[i].length <= 50
- All numbers contain only digits
'0'
to'9'
.
Solutions
Solution 1: Sorting + Prefix Checking
We can first sort the array \(\textit{numbers}\) based on the length of strings. Then, we iterate through each string \(\textit{s}\) in the array and check if there is any previous string \(\textit{t}\) that is a prefix of \(\textit{s}\). If such a string exists, it means there is a string that is a prefix of another string, so we return \(\textit{false}\). If we have checked all strings and haven't found any prefix relationships, we return \(\textit{true}\).
The time complexity is \(O(n^2 \times m + n \times \log n)\), and the space complexity is \(O(m + \log n)\), where \(n\) is the length of the array \(\textit{numbers}\), and \(m\) is the average length of strings in the array \(\textit{numbers}\).
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|