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'0' to '9'.We can first sort the array numbers based on the length of strings. Then, we iterate through each string s in the array and check if there is any previous string t that is a prefix of s. If such a string exists, it means there is a string that is a prefix of another string, so we return false. If we have checked all strings and haven't found any prefix relationships, we return 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 numbers, and m is the average length of strings in the array numbers.
Java
C++
Go
TypeScript
Practice Phone Number Prefix with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor