Skip to content

Instantly share code, notes, and snippets.

@ramhiser
Created December 15, 2015 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramhiser/969787f85b8306e6c984 to your computer and use it in GitHub Desktop.
Save ramhiser/969787f85b8306e6c984 to your computer and use it in GitHub Desktop.
Python snippet to remove any substrings of other strings in the list
from collections import defaultdict
def remove_substrings(words):
"""Remove any substrings of other strings in the list.
O(n) solution from...
Source: http://stackoverflow.com/a/24049808/234233
"""
longest = defaultdict(str)
for word in words: # O(n)
for i in range(1, len(word) + 1): # O(k)
for j in range(len(word) - i + 1): # O(k)
subword = word[j:j + i] # O(1)
if len(longest[subword]) < len(word): # O(1)
longest[subword] = word # O(1)
filtered_list = list(set(longest.values()))
# Keep original order
filtered_list = [s for s in words if s in filtered_list]
return filtered_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment