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.
1#include <stdbool.h>
2#include <string.h>
3
4bool areSentencesSimilar(char *sentence1, char *sentence2) {
5 char *s1_words[100], *s2_words[100];
6 int s1_count = 0, s2_count = 0;
7
8 char *token = strtok(sentence1, " ");
9 while(token != NULL) {
10 s1_words[s1_count++] = token;
11 token = strtok(NULL, " ");
12 }
13
14 token = strtok(sentence2, " ");
15 while(token != NULL) {
16 s2_words[s2_count++] = token;
17 token = strtok(NULL, " ");
18 }
19
20 int i = 0, j = 0;
21
22 while (i < s1_count && i < s2_count && strcmp(s1_words[i], s2_words[i]) == 0) {
23 i++;
24 }
25
26 while (j < s1_count - i && j < s2_count - i && strcmp(s1_words[s1_count - 1 - j], s2_words[s2_count - 1 - j]) == 0) {
27 j++;
28 }
29
30 return (i + j >= s1_count || i + j >= s2_count);
31}
32
This solution leverages strtok
to split the strings into words and uses two pointers, i
and j
, to iterate from the left and right. The solution successfully checks if the subsequences align in an overlapping manner.
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)
1
Using a list comprehension for the DP table, the Python solution proceeds with a structured double loop to solve the question via dynamic programming methodically.