#1813

Sentence Similarity III

Medium
ArrayTwo PointersStringTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution identifies the longest common prefix and suffix between the two sentences. If the remaining parts of the sentences after removing these parts are empty or can be matched, then the sentences are similar.

⚙️

Algorithm

4 steps
  1. 1Step 1: Split both sentences into lists of words.
  2. 2Step 2: Identify the longest common prefix by comparing words from the start.
  3. 3Step 3: Identify the longest common suffix by comparing words from the end.
  4. 4Step 4: Check if the remaining parts of both sentences can be made equal.
solution.py12 lines
1def areSentencesSimilar(sentence1, sentence2):
2    words1 = sentence1.split()
3    words2 = sentence2.split()
4    n1, n2 = len(words1), len(words2)
5    i, j = 0, 0
6    while i < n1 and j < n2 and words1[i] == words2[j]:
7        i += 1
8        j += 1
9    while i < n1 and j < n2 and words1[n1 - 1 - (i - j)] == words2[n2 - 1 - (j - i)]:
10        i += 1
11        j += 1
12    return i + j == n1 + n2

Complexity note: This complexity is efficient because we only traverse each sentence a limited number of times, specifically for prefix and suffix checks.

  • 1Identify common prefixes and suffixes to determine similarity.
  • 2Understanding how to manipulate strings can simplify complex problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.