Phone Directory
Learn how to solve the 'Phone Directory' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function phone_directory(contacts, query) that takes a list of unique strings contacts and a query string query. It should return a list of lists of strings, where the ith list contains the sorted contacts that match the prefix of query up to length i+1 (1-indexed). If no contact matches, return an empty list for that prefix.
- •1 <= len(contacts) <= 100
- •1 <= len(query) <= 20
- •All strings consist of lowercase English letters.
Examples
phone_directory(['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], 'gee')
[['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], ['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], ['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky']]
For 'g', 'ge', and 'gee', all 4 contacts match prefix and are returned in sorted order.
phone_directory(['mobile', 'mouse', 'moneypot', 'monitor', 'mousepad'], 'mouse')
[['mobile', 'monitor', 'moneypot', 'mouse', 'mousepad'], ['mobile', 'monitor', 'moneypot', 'mouse', 'mousepad'], ['mouse', 'mousepad'], ['mouse', 'mousepad'], ['mouse', 'mousepad']]
For prefix 'm' and 'mo', all contacts match. For 'mou', 'mous', and 'mouse', only 'mouse' and 'mousepad' match.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.