Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2452. Words Within Two Edits of Dictionary

ArrayStringTrie

Explanation:

To solve this problem, we can iterate through each word in the queries array and compare it with each word in the dictionary array. For each pair of words, we check if they are equal or if they can be made equal with at most two edits. We can achieve this by comparing the characters in both words and keeping track of the differences.

  1. For each word in queries, we iterate through each word in dictionary.
  2. If the words are equal, or if they can be made equal with at most two edits, we add the word from queries to the result list.
  3. We return the list of words from queries that match with some word from dictionary after a maximum of two edits.

Time complexity: O(n * m * k), where n is the number of words in queries, m is the number of words in dictionary, and k is the length of each word. Space complexity: O(n), where n is the number of words in queries.

:

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<String> wordMatches(String[] queries, String[] dictionary) {
        List<String> result = new ArrayList<>();
        
        for (String query : queries) {
            for (String word : dictionary) {
                if (query.equals(word) || areTwoEditsApart(query, word)) {
                    result.add(query);
                    break;
                }
            }
        }
        
        return result;
    }
    
    private boolean areTwoEditsApart(String word1, String word2) {
        int diffCount = 0;
        
        for (int i = 0; i < word1.length(); i++) {
            if (word1.charAt(i) != word2.charAt(i)) {
                diffCount++;
            }
            if (diffCount > 2) {
                return false;
            }
        }
        
        return true;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.