Phone Number Prefix - Problem

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.

A prefix is a substring that appears at the beginning of another string. For example, "123" is a prefix of "12345", but "234" is not a prefix of "12345".

Input & Output

Example 1 — Has Prefix
$ Input: numbers = ["123", "12", "456"]
Output: false
💡 Note: "12" is a prefix of "123", so return false
Example 2 — No Prefix
$ Input: numbers = ["123", "456", "789"]
Output: true
💡 Note: No number is a prefix of any other number
Example 3 — Single Digit Prefix
$ Input: numbers = ["1", "12", "123"]
Output: false
💡 Note: "1" is a prefix of both "12" and "123"

Constraints

  • 1 ≤ numbers.length ≤ 1000
  • 1 ≤ numbers[i].length ≤ 20
  • numbers[i] consists of digits only

Visualization

Tap to expand
Phone Number Prefix Problem INPUT String Array: numbers "123" index 0 "12" index 1 "456" index 2 Phone Numbers: 123 12 456 Check if any is prefix of another ALGORITHM STEPS 1 Sort by Length Sort numbers: ["12","123","456"] 2 Compare Each Pair Check startsWith() for pairs 3 Check "12" vs "123" "123".startsWith("12") = true "12" is prefix of "123" 4 Prefix Found! Return false immediately PREFIX MATCH DETECTED FINAL RESULT Prefix Relationship Found: "12" --> "123" "12" is prefix of "123" Output: false A phone number IS a prefix of another number. NOT VALID SET Key Insight: Sort the array first (by length or lexicographically). Then for each pair of adjacent strings, check if one is a prefix of another using startsWith(). Time: O(n log n + n*m) where m = max length. TutorialsPoint - Phone Number Prefix | Optimal Solution (Sorting + String Comparison)
Asked in
Google 45 Amazon 38 Microsoft 32
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen