LeetCode 3491: Phone Number Prefix Solution

Master LeetCode problem 3491 (Phone Number Prefix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3491. Phone Number Prefix

Problem Explanation

Explanation:

To solve this problem, we can iterate through the list of phone numbers and store the frequency of each unique prefix in a hashmap. We then iterate through the hashmap and check if the frequency equals the total number of phone numbers. If it does, we add the prefix to the result list. The time complexity of this solution is O(n) where n is the total number of characters in all phone numbers.

:

Solution Code

import java.util.*;

class Solution {
    public List<String> findPrefix(List<String> phoneNumbers) {
        Map<String, Integer> prefixFreq = new HashMap<>();
        List<String> result = new ArrayList<>();

        for (String number : phoneNumbers) {
            for (int i = 1; i <= number.length(); i++) {
                String prefix = number.substring(0, i);
                prefixFreq.put(prefix, prefixFreq.getOrDefault(prefix, 0) + 1);
            }
        }

        for (String prefix : prefixFreq.keySet()) {
            if (prefixFreq.get(prefix) == phoneNumbers.size()) {
                result.add(prefix);
            }
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3491 (Phone Number Prefix)?

This page provides optimized solutions for LeetCode problem 3491 (Phone Number Prefix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3491 (Phone Number Prefix)?

The time complexity for LeetCode 3491 (Phone Number Prefix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3491 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3491 in Java, C++, or Python.

Back to LeetCode Solutions