Leetcode 2452: Words Within Two Edits of Dictionary

grid47
grid47
Exploring patterns and algorithms
Mar 6, 2024 6 min read

You are given two arrays of strings, ‘queries’ and ‘dictionary’, where each word has the same length. A word from the ‘queries’ array can be transformed into a word from the ‘dictionary’ array by making at most two edits. An edit involves changing any character in the word to another letter. Your task is to find all words from ‘queries’ that, after making at most two edits, can match some word in ‘dictionary’. Return the words in the same order they appear in the ‘queries’.
Problem
Approach
Steps
Complexity
Input: The input consists of two arrays, 'queries' and 'dictionary', where each element in both arrays is a string of lowercase English letters.
Example: queries = ["hello", "world", "clue", "blue"], dictionary = ["blow", "hole", "blue"]
Constraints:
• 1 <= queries.length, dictionary.length <= 100
• n == queries[i].length == dictionary[j].length
• 1 <= n <= 100
• All queries[i] and dictionary[j] are composed of lowercase English letters.
Output: Return a list of words from 'queries' that can be transformed into a word from 'dictionary' with at most two edits.
Example: Output: ["hello", "blue"]
Constraints:
• The result list should contain the words in the same order they appear in 'queries'.
Goal: Find all words in 'queries' that can match some word from 'dictionary' after at most two edits.
Steps:
• 1. For each word in 'queries', compare it to each word in 'dictionary'.
• 2. Count the number of character mismatches between the words.
• 3. If the number of mismatches is less than or equal to two, add the word from 'queries' to the result list.
• 4. Return the result list containing all the words from 'queries' that match some word in 'dictionary'.
Goal: The solution should be efficient enough to handle the given constraints of word and array length.
Steps:
• The solution should be able to process up to 100 queries and dictionary words with lengths up to 100.
Assumptions:
• The words in 'queries' and 'dictionary' are all valid lowercase English letters.
Input: queries = ["hello", "world", "clue", "blue"], dictionary = ["blow", "hole", "blue"]
Explanation: The word 'hello' from queries can become 'blow' in the dictionary with one edit ('h' to 'b'). 'world' cannot match any word from the dictionary with two or fewer edits. 'clue' can become 'blue' with one edit ('c' to 'b'). Thus, the result is ["hello", "blue"].

Input: queries = ["apple", "grape", "melon"], dictionary = ["apricot", "grape", "mole"]
Explanation: The word 'apple' cannot match any word from the dictionary with at most two edits. 'grape' matches with 'grape' in the dictionary (no edits needed). 'melon' can be changed to 'mole' with one edit ('n' to 'e'). Hence, the result is ["grape", "melon"].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus