Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Longest Word in Dictionary through Deleting

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "524" 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

Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. Example 1: Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] Output: "apple" Example 2: Input: s = "abpcplea", dictionary = ["a","b","c"] Output: "a" Constraints: 1 <= s.length <= 1000 1 <= dictionary.length <= 1000 1 <= dictionary[i].length <= 1000 s and dictionary[i] consist of lowercase English letters.

Explanation

Here's a solution approach, complexity analysis, and the Python code:

  • Approach: Iterate through the dictionary. For each word in the dictionary, check if it can be formed by deleting characters from s. If it can, compare its length with the current longest word found so far. If it's longer, update the longest word. If it's the same length, choose the lexicographically smaller one.

  • Complexity:

    • Runtime: O(N M L), where N is the length of the dictionary, M is the average length of strings in the dictionary, and L is the length of string s.
    • Storage: O(1) - constant extra space.

Code

    def findLongestWord(s: str, dictionary: list[str]) -> str:
    """
    Given a string s and a string array dictionary, return the longest string in the dictionary
    that can be formed by deleting some of the given string characters.
    If there is more than one possible result, return the longest word with the smallest
    lexicographical order. If there is no possible result, return the empty string.
    """
    longest_word = ""

    for word in dictionary:
        i = 0
        j = 0
        while i < len(s) and j < len(word):
            if s[i] == word[j]:
                j += 1
            i += 1

        if j == len(word):  # word can be formed from s
            if len(word) > len(longest_word):
                longest_word = word
            elif len(word) == len(longest_word) and word < longest_word:
                longest_word = word

    return longest_word

More from this blog

C

Chatmagic blog

2894 posts