mediumStringsPattern: Mixed
Maximum Non-overlapping Substring Matches Solution
Problem Statement
Given an array of strings and an array of target strings, find the maximum number of non-overlapping substrings in the target array that are present in the string array.
Examples
Example 1:
Input:{"substrings": ['abc', 'xy', '123'], "targets": ['x', '123', 'zy', 'xyz', 'abc', 'abxyz', 'xyzxyz']}
Output:5
Explanation: We can find five non-overlapping substrings 'x', '123', 'xyz', 'abc' and 'xyz'.
Constraints
- The input arrays will only contain strings.
- The output will always be a non-negative integer.
- The input arrays will only contain a finite number of strings.
Time: O(n*m*arrayLength + t*targetLength) Space: O(n*m)
A more efficient approach would be to use a HashMap to store the strings from the string array. Then, traverse the target array and for each target string, check if it exists in the HashMap. This approach has a linear time complexity as we have to traverse each string and target string once.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
arr = sys.stdin.readline().strip().split(",")
target = sys.stdin.readline().strip().split(",")
max_count = 0
for i in range(len(target)):
substrings = [s for s in arr if s in target[i]]
substrings.sort(key=len, reverse=True)
last_index = -1
current_count = 0
for k in range(len(substrings)):
index = target[i].find(substrings[k], last_index + 1)
if index !== -1:
current_count += 1
last_index = index + len(substrings[k]) - 1
max_count += current_count
print(max_count)