Skip to main content

Prefix and Suffix Search


Given a list of words and a target string, find the words in the list that have the same prefix or suffix as the target string.

Example 1
words = ["apple", "app", "apricot", "apricots", "apron", "apply", "appeal"]

prefix = "ap"

Suffix = "le"

["apple", "appeal"]


all//Prefix and Suffix

# Prefix and Suffix Search Algorithm
# Input:
# string s - the string to search
# list of strings words - the words to search for
# Output:
# list of strings - the words found in s

def prefix_suffix_search(s, words):
# Create an empty result list
result = []

# Iterate over each word in the list
for word in words:
# Check if the word is a prefix or suffix of s
if s.startswith(word) or s.endswith(word):
# Append the word to the result list

# Return the result list
return result