Back to Practice Dashboard
Competitive ProgrammingEasy

Phone Directory

Learn how to solve the 'Phone Directory' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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.

Constraints
  • 1 <= len(contacts) <= 100
  • 1 <= len(query) <= 20
  • All strings consist of lowercase English letters.

Examples

Example 1
Input
phone_directory(['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], 'gee')
Output
[['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], ['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky'], ['geeikist', 'geeksforgeeks', 'geeksfortest', 'geeky']]
Explanation

For 'g', 'ge', and 'gee', all 4 contacts match prefix and are returned in sorted order.

Example 2
Input
phone_directory(['mobile', 'mouse', 'moneypot', 'monitor', 'mousepad'], 'mouse')
Output
[['mobile', 'monitor', 'moneypot', 'mouse', 'mousepad'], ['mobile', 'monitor', 'moneypot', 'mouse', 'mousepad'], ['mouse', 'mousepad'], ['mouse', 'mousepad'], ['mouse', 'mousepad']]
Explanation

For prefix 'm' and 'mo', all contacts match. For 'mou', 'mous', and 'mouse', only 'mouse' and 'mousepad' match.

Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
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.

Open in Editor