Phone Directory
Detailed guide and Python implementation for the 'Phone Directory' problem.
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 input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.