881355. Case Insensitive Search

Medium

Case Insensitive Search

Summary

The case insensitive search problem involves finding a given pattern in a string while ignoring the case (i.e., treating uppercase and lowercase letters as the same). This problem is related to strings and pattern searching.

Detailed Explanation

To solve this problem, we can use a simple approach by converting both the target string and the search pattern into either all uppercase or all lowercase before performing the search. This way, we can ensure that the comparison is case-insensitive.

Here's a step-by-step breakdown of the solution:

  1. Convert the target string and the search pattern into either all uppercase or all lowercase.
  2. Compare each character in the target string with the corresponding character in the search pattern (after conversion).
  3. If the characters match, return the starting index of the pattern in the target string.

Here's a sample ASCII art diagram to illustrate the process:

Target String:  Hello World
Search Pattern: hello

1. Convert both strings to lowercase:
    Target String:  hello world
    Search Pattern: hello

2. Compare characters:
    'h' (target) == 'h' (pattern)
    'e' (target) == 'e' (pattern)
    ...
3. Return the starting index of the pattern in the target string: 0

Time complexity for this solution is O(n), where n is the length of the target string, as we need to iterate through each character in the target string once. Space complexity is O(1), as we only require a constant amount of space to store the converted strings.

Optimized Solutions

Java

View on GeeksforGeeks
public int caseInsensitiveSearch(String target, String pattern) {
    int targetLength = target.length();
    int patternLength = pattern.length();

    for (int i = 0; i <= targetLength - patternLength; i++) {
        boolean match = true;
        for (int j = 0; j < patternLength; j++) {
            if (Character.toLowerCase(target.charAt(i + j)) != Character.toLowerCase(pattern.charAt(j))) {
                match = false;
                break;
            }
        }
        if (match) return i;
    }

    return -1;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.