Welcome to Subscribe On Youtube
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}$.
-
class Solution { public boolean phonePrefix(String[] numbers) { Arrays.sort(numbers, (a, b) -> Integer.compare(a.length(), b.length())); for (int i = 0; i < numbers.length; i++) { String s = numbers[i]; for (int j = 0; j < i; j++) { if (s.startsWith(numbers[j])) { return false; } } } return true; } }
-
#include <ranges> class Solution { public: bool phonePrefix(vector<string>& numbers) { ranges::sort(numbers, [](const string& a, const string& b) { return a.size() < b.size(); }); for (int i = 0; i < numbers.size(); i++) { if (ranges::any_of(numbers | views::take(i), [&](const string& t) { return numbers[i].starts_with(t); })) { return false; } } return true; } };
-
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
-
func phonePrefix(numbers []string) bool { sort.Slice(numbers, func(i, j int) bool { return len(numbers[i]) < len(numbers[j]) }) for i, s := range numbers { for _, t := range numbers[:i] { if strings.HasPrefix(s, t) { return false } } } return true }
-
function phonePrefix(numbers: string[]): boolean { numbers.sort((a, b) => a.length - b.length); for (let i = 0; i < numbers.length; i++) { for (let j = 0; j < i; j++) { if (numbers[i].startsWith(numbers[j])) { return false; } } } return true; }