LeetCode 2301: Match Substring After Replacement Solution

Master LeetCode problem 2301 (Match Substring After Replacement), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2301. Match Substring After Replacement

Problem Explanation

Explanation

To solve this problem, we can iterate through each mapping and try to replace the characters in the sub string accordingly. We then check if the modified sub string is a substring of the given string s. We can use a set to keep track of characters that have already been replaced in the sub string to ensure that each character is replaced at most once.

  • Algorithm:

    1. Iterate through each mapping and try to replace characters in the sub string.
    2. Use a set to keep track of characters that have already been replaced.
    3. Check if the modified sub string is a substring of s.
    4. Return true if a valid replacement is found, otherwise return false.
  • Time Complexity: O(n*m) where n is the length of sub and m is the number of mappings.

  • Space Complexity: O(n) where n is the length of sub.

Solution Code

class Solution {
    public boolean isSubString(String s, String sub, String[][] mappings) {
        Set<Character> replacedChars = new HashSet<>();
        
        char[] subChars = sub.toCharArray();
        for (String[] mapping : mappings) {
            char oldChar = mapping[0].charAt(0);
            char newChar = mapping[1].charAt(0);
            
            for (int i = 0; i < subChars.length; i++) {
                if (subChars[i] == oldChar && !replacedChars.contains(oldChar)) {
                    subChars[i] = newChar;
                    replacedChars.add(oldChar);
                }
            }
        }
        
        String modifiedSub = new String(subChars);
        return s.contains(modifiedSub);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2301 (Match Substring After Replacement)?

This page provides optimized solutions for LeetCode problem 2301 (Match Substring After Replacement) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2301 (Match Substring After Replacement)?

The time complexity for LeetCode 2301 (Match Substring After Replacement) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2301 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2301 in Java, C++, or Python.

Back to LeetCode Solutions