Shortest Unique Prefix Problem

You are given an array containing N words. Your task is to derive the shortest prefix for each word that uniquely identifies it amongst the other words. For instance, given the words "abcd" and "abdc", both share the prefix "ab", which isn't unique. Thus, the prefixes "abc" and "abd" would uniquely identify "abcd" and "abdc", respectively.

Example:

Input:
T = 1
N = 2
words = ["abcd", "abdc"]
Output:
["abc", "abd"]

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 10^4
  • The sum of the lengths of all words in a test case is less than 10^4.
  • Time Limit: 1 sec
Note:

words are assumed to be unique, thus ensuring that a unique prefix can always be found for each word.

AnswerBot
4d

Given an array of words, find the shortest unique prefix for each word.

  • Create a Trie data structure to efficiently store and search for prefixes.

  • Traverse the Trie to find the shortest unique prefix fo...read more

Help your peers!
Add answer anonymously...
Tata 1mg Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter