We can represent a sentence as an array of words. For example, the sentence "I am happy with leetcode" can be represented as arr = ["I","am","happy","with","leetcode"].
Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two words xi and yi are similar.
Return true if sentence1 and sentence2 are similar, or false if they are not similar.
Two sentences are similar if:
They have the same length (i.e., the same number of words)
sentence1[i] and sentence2[i] are similar for all i
Note: A word is always similar to itself. The similarity relation is not transitive. For example, if words a and b are similar, and words b and c are similar, a and c are not necessarily similar.
💡 Note:Both sentences have length 2. Position 0: "great" and "fine" are not identical and there's no direct similarity pair ["great","fine"] or ["fine","great"]. Since similarity is not transitive, having both relate to "good" doesn't make them similar to each other.
The key insight is to efficiently check word similarity using a hash set. The optimal approach builds a hash set of all similarity pairs (bidirectional) for O(1) lookup, then compares each word position. Time: O(m + n), Space: O(m).
Common Approaches
✓
Brute Force Linear Search
⏱️ Time: O(n × m)
Space: O(1)
Check if sentences have same length, then for each position, search through all similarity pairs to see if the words are similar or identical.
Hash Set Optimization
⏱️ Time: O(m + n)
Space: O(m)
First pass builds a hash set containing all similarity pairs (both directions). Second pass checks each word pair against the hash set for instant lookup.
Brute Force Linear Search — Algorithm Steps
Check if both sentences have the same length
For each word position, check if words are identical or find them in similarity pairs
Return false if any pair is not similar
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Check Lengths
Verify both sentences have same number of words
2
Compare Each Position
For each word pair, search all similarity pairs
3
Result
Return true if all positions are similar
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
static char sentence1[100][101];
static char sentence2[100][101];
static char similarPairs[1000][2][101];
bool solution(int len1, int len2, int pairsLen) {
if (len1 != len2) {
return false;
}
for (int i = 0; i < len1; i++) {
if (strcmp(sentence1[i], sentence2[i]) == 0) {
continue;
}
bool found = false;
for (int j = 0; j < pairsLen; j++) {
if ((strcmp(similarPairs[j][0], sentence1[i]) == 0 && strcmp(similarPairs[j][1], sentence2[i]) == 0) ||
(strcmp(similarPairs[j][0], sentence2[i]) == 0 && strcmp(similarPairs[j][1], sentence1[i]) == 0)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
int parseStringArray(char* line, char arr[][101]) {
int count = 0;
if (strcmp(line, "[]") == 0) {
return 0;
}
int len = strlen(line);
for (int i = 1; i < len - 1; i++) {
if (line[i] == '"') {
int j = i + 1;
while (line[j] != '"') {
j++;
}
int wordLen = j - i - 1;
strncpy(arr[count], line + i + 1, wordLen);
arr[count][wordLen] = '\0';
count++;
i = j;
}
}
return count;
}
int parsePairs(char* line) {
int count = 0;
if (strcmp(line, "[]") == 0) {
return 0;
}
int len = strlen(line);
int i = 1; // Skip opening '['
while (i < len - 1) {
if (line[i] == '[') {
i++; // Skip '['
// Find opening quote of first string
while (line[i] != '"') i++;
i++; // Skip opening quote
int start = i;
// Parse first string
while (line[i] != '"') i++; // Find closing quote
int wordLen = i - start;
strncpy(similarPairs[count][0], line + start, wordLen);
similarPairs[count][0][wordLen] = '\0';
i++; // Skip closing quote
// Skip comma and whitespace
while (line[i] == ',' || line[i] == ' ') i++;
// Find opening quote of second string
while (line[i] != '"') i++;
i++; // Skip opening quote
start = i;
// Parse second string
while (line[i] != '"') i++; // Find closing quote
wordLen = i - start;
strncpy(similarPairs[count][1], line + start, wordLen);
similarPairs[count][1][wordLen] = '\0';
i++; // Skip closing quote
// Skip to ']'
while (line[i] != ']') i++;
i++; // Skip ']'
count++;
}
i++;
}
return count;
}
int main() {
char line[10000];
int len1, len2, pairsLen;
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
len1 = parseStringArray(line, sentence1);
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
len2 = parseStringArray(line, sentence2);
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0';
pairsLen = parsePairs(line);
bool result = solution(len1, len2, pairsLen);
printf(result ? "true\n" : "false\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n × m)
n words to check, each requiring O(m) search through m similarity pairs
n
2n
✓ Linear Growth
Space Complexity
O(1)
Only using constant extra variables
n
2n
✓ Linear Space
28.4K Views
MediumFrequency
~15 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.