10. Find the Longest String
β GFG solution to the Find the Longest String problem: find the longest string where every prefix exists in the array using efficient prefix validation technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given an array of strings words[]
, find the longest string in words[]
such that every prefix of it is also present in the array words[]
.
If multiple strings have the same maximum length, return the lexicographically smallest one.
π Examples
Example 1
Input: words[] = ["p", "pr", "pro", "probl", "problem", "pros", "process", "processor"]
Output: pros
Explanation: "pros" is the longest word with all prefixes ("p", "pr", "pro", "pros") present in the array words[].
Example 2
Input: words[] = ["ab", "a", "abc", "abd"]
Output: abc
Explanation: Both "abc" and "abd" has all the prefixes in words[]. Since, "abc" is lexicographically smaller than "abd", so the output is "abc".
π Constraints
$1 \le \text{words.length} \le 10^3$
$1 \le \text{words}[i].\text{length} \le 10^3$
β
My Approach
The optimal approach uses Sorting combined with Hash Set for efficient prefix validation:
Sorting + Hash Set Validation
Sort the Array:
Sort the words array to ensure lexicographical order.
This guarantees that when we find a valid string, it's the lexicographically smallest among strings of the same length.
Initialize Data Structures:
Use an
unordered_set
to store valid strings (those whose all prefixes exist).Initialize result string as empty.
Validate Each Word:
For each word in the sorted array:
If word length is 1 (single character), it's automatically valid.
Otherwise, check if the prefix (word without last character) exists in the set.
If valid, add the word to the set and update result if it's longer.
Prefix Validation:
For a word to be valid, all its prefixes must exist in the array.
We build valid strings incrementally, ensuring each new string's prefix is already validated.
Lexicographical Ordering:
Sorting ensures that among strings of equal length, the lexicographically smallest is processed first.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n + nm), where n is the number of words and m is the average length of words. The sorting takes O(n log n) and prefix validation takes O(nm) time.
Expected Auxiliary Space Complexity: O(n*m), where n is the number of words and m is the average length of words for storing valid strings in the hash set.
π§βπ» Code (C++)
class Solution {
public:
string longestString(vector<string>& words) {
sort(words.begin(), words.end());
unordered_set<string> st;
string res = "";
for (string& w : words) {
if (w.length() == 1 || st.count(w.substr(0, w.length() - 1))) {
st.insert(w);
if (w.length() > res.length()) res = w;
}
}
return res;
}
};
π§βπ» Code (Java)
class Solution {
public String longestString(String[] words) {
Arrays.sort(words);
Set<String> st = new HashSet<>();
String res = "";
for (String w : words) {
if (w.length() == 1 || st.contains(w.substring(0, w.length() - 1))) {
st.add(w);
if (w.length() > res.length()) {
res = w;
}
}
}
return res;
}
}
π Code (Python)
class Solution:
def longestString(self, words):
words.sort()
st = set()
res = ""
for w in words:
if len(w) == 1 or w[:-1] in st:
st.add(w)
if len(w) > len(res):
res = w
return res
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated