Given two lists of strings, A and B, count how many pairs (a, b) can be formed such that a is a prefix of b and a is in list A, and b is in list B.
A and B are lists of non-empty strings consisting of only lowercase English letters.A are prefixes of strings from B.A and B?
A and B?
a in list A and each string b in list B.a is a prefix of b.a is a prefix of b.Here’s the implementation of the brute-force method to solve the problem:
def count_prefix_suffix_pairs(A, B):
count = 0
for a in A:
for b in B:
if b.startswith(a):
count += 1
return count
# Example usage
A = ["a", "b", "ab"]
B = ["ab", "bc", "abc"]
print(count_prefix_suffix_pairs(A, B)) # Output should be 4
ABB (for prefix checking)This brute-force solution should be efficient enough for moderate-sized lists. If the input lists are extremely large, further optimizations would be warranted.
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?