Longest Word in Dictionary through Deleting — LeetCode 524 Python Solution

MediumArrayTwo PointersStringSorting
Problem
#524
Reading time
3 min

The problem

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.

Example

Input
s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output
"apple"

Python solution

Python
class Solution:
    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
        def check(s: str, t: str) -> bool:
            m, n = len(s), len(t)
            i = j = 0
            while i < m and j < n:
                if s[i] == t[j]:
                    i += 1
                j += 1
            return i == m

        ans = ""
        for t in dictionary:
            if check(t, s) and (len(ans) < len(t) or (len(ans) == len(t) and ans > t)):
                ans = t
        return ans

Complexity

MeasureComplexity
TimeO(d \times (m + n)), where d is the length of the string list, and m and n are the lengths of string s and the average length of strings in the list, respectively
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 524. Longest Word in Dictionary through Deleting is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 524. Longest Word in Dictionary through Deleting?
LeetCode 524. Longest Word in Dictionary through Deleting is rated Medium on LeetCode.
What is the time complexity of LeetCode 524. Longest Word in Dictionary through Deleting?
The Python solution on this page runs in O(d \times (m + n)), where d is the length of the string list, and m and n are the lengths of string s and the average length of strings in the list, respectively.
What is the space complexity of LeetCode 524. Longest Word in Dictionary through Deleting?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 524. Longest Word in Dictionary through Deleting cover?
LeetCode 524. Longest Word in Dictionary through Deleting is tagged Array, Two Pointers, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview