Sponsored
Sponsored
The Two Pointers technique involves using two indices that move towards each other from the start and end of the lists. This approach effectively captures the prefixes and suffixes.
By using two pointers, we move from the start to the first words that don't match and from the end to the first words that also don't match. If the pointers end up crossing or are equal, the sentences are considered similar. We exploit the fact that any dissimilar portion in the middle, if any, can be 'inserted'.
Time Complexity: O(n + m), where n and m are the lengths of sentence1 and sentence2 respectively.
Space Complexity: O(n + m) for storing words.
1function areSentencesSimilar(sentence1, sentence2) {
2 const s1_words = sentence1.split(' ');
3 const s2_words = sentence2.split(' ');
4
5 let i = 0, j = 0;
6
7 while (i < s1_words.length && i < s2_words.length && s1_words[i] === s2_words[i]) {
8 i++;
9 }
10
11 while (j < s1_words.length - i && j < s2_words.length - i &&
12 s1_words[s1_words.length - j - 1] === s2_words[s2_words.length - j - 1]) {
13 j++;
14 }
15
16 return (i + j >= s1_words.length || i + j >= s2_words.length);
17}
18
JavaScript's use of split
allows simple conversion to word arrays, and the solution efficiently checks prefixes and suffixes using for loops.
Another approach is to utilize a dynamic programming table to store sub-problems results. You can construct a DP table where dp[i][j]
indicates whether the first i
words from sentence1
can match the first j
words from sentence2
. This could be expanded using insertion strategies for any non-matching sub-sequences.
This approach relies more on systematic computation than geometric traversal, but can be more memory intensive.
Time Complexity: O(n*m)
Space Complexity: O(n*m)
#include <vector>
using namespace std;
bool areSentencesSimilar(string sentence1, string sentence2) {
vector<string> s1_words, s2_words;
stringstream ss1(sentence1), ss2(sentence2);
string word;
while(ss1 >> word) {
s1_words.push_back(word);
}
while(ss2 >> word) {
s2_words.push_back(word);
}
vector<vector<bool>> dp(s1_words.size() + 1, vector<bool>(s2_words.size() + 1, false));
dp[0][0] = true;
for(int i = 0; i <= s1_words.size(); ++i) {
for(int j = 0; j <= s2_words.size(); ++j) {
if (i > 0 && j > 0 && s1_words[i-1] == s2_words[j-1])
dp[i][j] = dp[i-1][j-1];
else if (i > 0)
dp[i][j] = dp[i-1][j] || dp[i][j];
else if (j > 0)
dp[i][j] = dp[i][j-1] || dp[i][j];
}
}
return dp[s1_words.size()][s2_words.size()];
}
This C++ solution employs a 2D vector to represent the DP table. The entries are populated in loops based on word comparison or prior computation results.