Program to check whether two sentences are similar or not in Python

Two sentences are considered similar when we can transform one sentence into another by adding words at the beginning, end, or both. This means one sentence can be a subsequence of another with additional words only at the edges.

For example, if we have "we live at city Kolkata" and "city Kolkata", they are similar because we can add "we live at " to the beginning of the second sentence to get the first one.

Algorithm

To check if two sentences are similar, we follow these steps ?

  • Split both sentences into word lists

  • Ensure the shorter sentence is processed first

  • Match words from both ends (beginning and end)

  • If all words of the shorter sentence are matched, return True

  • If any word cannot be matched from either end, return False

Implementation

Here's the complete solution ?

def check_similar_sentences(s, t):
    # Split sentences into word lists
    s1 = s.split()
    s2 = t.split()
    
    # Ensure s1 is the shorter sentence
    if len(s1) > len(s2):
        s1, s2 = s2, s1
    
    # Match words from both ends
    while s1:
        if s2[0] == s1[0]:
            # Match from beginning
            s2.pop(0)
            s1.pop(0)
        elif s2[-1] == s1[-1]:
            # Match from end
            s2.pop()
            s1.pop()
        else:
            # No match possible
            return False
    
    return True

# Test the function
s = "we live at city Kolkata"
t = "city Kolkata"
result = check_similar_sentences(s, t)
print(f"Are '{s}' and '{t}' similar? {result}")
Are 'we live at city Kolkata' and 'city Kolkata' similar? True

How It Works

Let's trace through the example step by step ?

def trace_similarity(s, t):
    s1 = s.split()
    s2 = t.split()
    
    print(f"Original: s1 = {s1}, s2 = {s2}")
    
    if len(s1) > len(s2):
        s1, s2 = s2, s1
        print(f"Swapped: s1 = {s1}, s2 = {s2}")
    
    step = 1
    while s1:
        print(f"Step {step}: s1 = {s1}, s2 = {s2}")
        
        if s2[0] == s1[0]:
            print(f"  Matching from beginning: '{s2[0]}' == '{s1[0]}'")
            s2.pop(0)
            s1.pop(0)
        elif s2[-1] == s1[-1]:
            print(f"  Matching from end: '{s2[-1]}' == '{s1[-1]}'")
            s2.pop()
            s1.pop()
        else:
            print(f"  No match found!")
            return False
        
        step += 1
    
    print("All words matched successfully!")
    return True

# Test with example
s = "we live at city Kolkata"
t = "city Kolkata"
result = trace_similarity(s, t)
print(f"\nResult: {result}")
Original: s1 = ['we', 'live', 'at', 'city', 'Kolkata'], s2 = ['city', 'Kolkata']
Swapped: s1 = ['city', 'Kolkata'], s2 = ['we', 'live', 'at', 'city', 'Kolkata']
Step 1: s1 = ['city', 'Kolkata'], s2 = ['we', 'live', 'at', 'city', 'Kolkata']
  Matching from end: 'Kolkata' == 'Kolkata'
Step 2: s1 = ['city'], s2 = ['we', 'live', 'at', 'city']
  Matching from end: 'city' == 'city'
All words matched successfully!

Result: True

Additional Examples

Let's test with more examples to understand the concept better ?

def test_multiple_cases():
    test_cases = [
        ("hello world", "world", True),
        ("I am happy today", "am happy", True),
        ("python is great", "java is great", False),
        ("a b c d", "b c", True),
        ("same sentence", "same sentence", True)
    ]
    
    for s, t, expected in test_cases:
        result = check_similar_sentences(s, t)
        status = "?" if result == expected else "?"
        print(f"{status} '{s}' & '{t}' ? {result}")

test_multiple_cases()
? 'hello world' & 'world' ? True
? 'I am happy today' & 'am happy' ? True
? 'python is great' & 'java is great' ? False
? 'a b c d' & 'b c' ? True
? 'same sentence' & 'same sentence' ? True

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the shorter sentence

  • Space Complexity: O(m + n), where m and n are the lengths of both sentences for storing word lists

Conclusion

This algorithm efficiently checks sentence similarity by matching words from both ends of the sentences. The key insight is that additional words can only be added at the beginning or end, making this greedy approach work perfectly for the problem.

Updated on: 2026-03-26T14:38:54+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements