Skip to main content

Prefix and Suffix Search

Question

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
Input:
words = ["apple", "app", "apricot", "apricots", "apron", "apply", "appeal"]

prefix = "ap"

Suffix = "le"

Output:
["apple", "appeal"]

Solution

all//Prefix and Suffix Search.py


# 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
result.append(word)

# Return the result list
return result