Leetcode 820. Short Encoding of Words
820. Short Encoding of Words
Given a list of words, words
, each word can be written as a reference string (i.e., a string that directly references some previous written string in the encoding). Specifically, the reference string for a word-a can either be the word-a itself, or a suffix of word-a. More formally, a suffix of the reference string of a word is formed as follows:
word[i:]
is present in the encoding list, then word
can be encoded using word[i:]
.Your task is to find the length of the shortest reference string that can encode all words in the given list.
Example 1:
Input: words = ["time", "me", "bell"]
Output: 10
Explanation: "time" and "bell" both have no proper suffixes in the list, while "me" is a suffix of "time". So the encoding is "time#bell#" and its length is 10.
Based on common constraints in problems like this, we can assume:
0
.Steps:
#include <iostream>
#include <vector>
#include <unordered_set>
#include <string>
using namespace std;
int minimumLengthEncoding(vector<string>& words) {
unordered_set<string> uniqueSuffixes;
// Add all suffixes of each word to the set
for (const auto& word : words) {
for (int i = 0; i < word.size(); ++i) {
uniqueSuffixes.insert(word.substr(i));
}
}
// Remove suffixes that are themselves suffixes of others
for (const auto& word : words) {
for (int i = 1; i < word.size(); ++i) {
uniqueSuffixes.erase(word.substr(i));
}
}
// Calculate the length of the final encoded string
int totalLength = 0;
for (const auto& suffix : uniqueSuffixes) {
totalLength += suffix.size() + 1; // +1 for the '#' character
}
return totalLength;
}
int main() {
vector<string> words = {"time", "me", "bell"};
cout << "Output: " << minimumLengthEncoding(words) << endl;
return 0;
}
The time complexity of this solution is influenced by:
n
is the number of words and k
is the average length of words.Thus, the overall time complexity is O(n*k^2). However, this should be efficient for typical word list constraints found in coding interview problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?