#820

Short Encoding of Words

Medium
ArrayHash TableStringTrieHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

The optimal approach leverages the fact that we can avoid duplicating parts of words by only encoding the unique suffixes. By storing the words in a set, we can efficiently check for overlaps and minimize the reference string length.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a set to store all words.
  2. 2Step 2: For each word, check if it is a suffix of any other word in the set.
  3. 3Step 3: If not, add the length of the word plus one (for the '#') to the total length.
  4. 4Step 4: Return the total length.
solution.py8 lines
1# Full working Python code
2words = ['time', 'me', 'bell']
3word_set = set(words)
4total_length = 0
5for word in words:
6    if not any(word != other and other.endswith(word) for other in word_set):
7        total_length += len(word) + 1
8print(total_length)

Complexity note: This complexity arises because we check each word against all others, where `m` is the average length of the words. The space complexity is due to storing the words in a set.

  • 1Understanding suffix relationships between words can help minimize the reference string length.
  • 2Using data structures like sets can improve lookup times and help manage word uniqueness.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.