Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Uncommon Words from Two Sentences

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "884" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order. Example 1: Input: s1 = "this apple is sweet", s2 = "this apple is sour" Output: ["sweet","sour"] Explanation: The word "sweet" appears only in s1, while the word "sour" appears only in s2. Example 2: Input: s1 = "apple apple", s2 = "banana" Output: ["banana"] Constraints: 1 <= s1.length, s2.length <= 200 s1 and s2 consist of lowercase English letters and spaces. s1 and s2 do not have leading or trailing spaces. All the words in s1 and s2 are separated by a single space.

Explanation

Here's a breakdown of the approach, followed by the code:

  • Count Word Frequencies: Use a hash map (dictionary in Python) to store the frequency of each word in both sentences combined.
  • Identify Uncommon Words: Iterate through the frequency map and identify words that appear exactly once.
  • Filter Uncommon Words: Construct the list of uncommon words and return.

  • Runtime Complexity: O(m + n), where m and n are the lengths of the input strings s1 and s2, respectively. This is due to iterating through the strings to count word frequencies. Storage Complexity: O(m + n) in the worst case, where m and n are the number of unique words in s1 and s2, respectively. This is because the hash map stores all the unique words and their counts.

Code

    def uncommonFromSentences(s1: str, s2: str) -> list[str]:
    """
    Given two sentences s1 and s2, return a list of all the uncommon words.
    A word is uncommon if it appears exactly once in one of the sentences,
    and does not appear in the other sentence.
    """

    word_counts = {}

    for word in s1.split():
        word_counts[word] = word_counts.get(word, 0) + 1

    for word in s2.split():
        word_counts[word] = word_counts.get(word, 0) + 1

    uncommon_words = [word for word, count in word_counts.items() if count == 1]

    return uncommon_words

More from this blog

C

Chatmagic blog

2894 posts