Leetcode 1408. String Matching in an Array
Given an array of string words
, return all strings in words
that are a substring of another word in any order. A substring
is a contiguous sequence of characters within a string.
#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
using namespace std;
vector<string> stringMatching(vector<string>& words) {
unordered_set<string> resultSet;
for (size_t i = 0; i < words.size(); i++) {
for (size_t j = 0; j < words.size(); j++) {
if (i != j && words[j].find(words[i]) != string::npos) {
resultSet.insert(words[i]);
break; // No need to check further if we've found at least one match
}
}
}
return vector<string>(resultSet.begin(), resultSet.end());
}
int main() {
vector<string> words = {"mass", "as", "hero", "superhero"};
vector<string> result = stringMatching(words);
for (const string& word : result) {
cout << word << " ";
}
return 0;
}
Time Complexity: The time complexity is (O(n^2 \cdot m)), where (n) is the size of the words
vector and (m) is the average length of words. This complexity arises because we are comparing each pair of words and performing a substring search which, in the worst case, is linear with respect to the length of the word.
Space Complexity: The space complexity is (O(n)) because we store the results in a set which, in the worst case, could store all words.
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?