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.

3303. Find the Occurrence of First Almost Equal Substring

Explanation

To solve this problem, we can use a sliding window approach. We will iterate through the string s using a window of size equal to the length of pattern. At each step, we will check if the current substring within the window is almost equal to the pattern by allowing at most one character to be different.

We will keep track of the number of differences between the current substring and the pattern. If the number of differences is greater than 1, we will shrink the window by incrementing the left pointer. If the number of differences is at most 1, we will update the minimum starting index of the substring that is almost equal to the pattern.

Finally, we return the smallest starting index found or -1 if no such index exists.

Time Complexity: O(n), where n is the length of the string s. Space Complexity: O(1)

class Solution {
    public int findTheOccurrenceOfFirstAlmostEqualSubstring(String s, String pattern) {
        int left = 0, right = 0;
        int diffCount = 0;
        int minStart = -1;
        
        while (right < s.length()) {
            if (s.charAt(right) != pattern.charAt(right)) {
                diffCount++;
            }
            while (diffCount > 1) {
                if (s.charAt(left) != pattern.charAt(left)) {
                    diffCount--;
                }
                left++;
            }
            if (right - left + 1 == pattern.length()) {
                if (minStart == -1 || left < minStart) {
                    minStart = left;
                }
            }
            right++;
        }
        
        return minStart;
    }
}

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.