Longest word with all prefixes

Tries Problems Hard

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