Longest word with all prefixes

Tries Problems Hard
  • This programming problem employs a concept often used in search engine algorithms for keyword searching and for autocompletion features in user interface design
  • For instance, when typing in a search engine or web address in a browser, the system relies on similar logic to suggest lexicographically sorted completions based on previous input or commonly used phrases
  • The ability to efficiently solve this type of problem has real-world impacts on enhancing user experience and speeding up input tasks - something we take for granted every day!

Given a string array nums of length n. A string is called a complete string if every prefix of this string is also present in the array nums. Find the longest complete string in the array nums.

If there are multiple strings with the same length, return the lexicographically smallest one and if no string exists, return "None" (without quotes).

Examples:

Input : nums = [ "n", "ni", "nin", "ninj" , "ninja" , "nil" ]

Output : ninja

Explanation : The word "ninja" is the longest word which has all its prefixes present in the array.

Input : nums = [ "ninja" , "night" , "nil" ]

Output : None

Explanation : There is no string that has all its prefix present in array. So we return None.

Input : nums = [ "cat" , "car" , "cow", "c", "ca", "t", "r", "w" ]

Constraints

  • 1 <= n <= 105
  • 1 <= nums[i].length <= 104
  • nums[i] consist only of lowercase English characters

Hints

  • Build a Trie from the given array while marking the end of each word. Additionally, store a flag at each node to indicate whether this prefix exists in nums.
  • "Find the longest complete string by iterating through nums and checking whether every prefix of a word exists in the Trie. Maintain a variable to track the longest valid string. If two strings have the same length, return the lexicographically smallest one."

Company Tags

Nutanix AMD Rakuten IBM Chewy Seagate Technology Walmart Qualcomm Ernst & Young Etsy Goldman Sachs Red Hat Rockstar Games Byju's American Express Oracle Optum Ubisoft Databricks Bain & Company Lyft NVIDIA Dropbox GE Healthcare Roblox Google Microsoft Amazon Meta Apple Netflix Adobe