VOOZH about

URL: https://www.geeksforgeeks.org/dsa/case-insensitive-search/

⇱ Case Insensitive Search - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Case Insensitive Search

Last Updated : 23 Jul, 2025

Given two strings txt and pat, the task is to return all indices of occurrences of pat within txt, ignoring the letter case (uppercase and lowercase characters are considered same).

Examples:

Input: txt = "aBcAb", pat = "aB"
Output: [0, 3]
Explanation: The string "ab" can match with any of the following strings: "ab", "Ab", "aB" and "AB". So, pat occurs twice in txt, first occurrence starts from index 0 and second from index 3.

Input: txt = "aAAa", pat = "Aa"
Output: [0, 1, 2]
Explanation: The string "Aa" can match with any of the following strings: "aa", "aA", "Aa" and "AA". So, pat occurs thrice in txt, first occurrence starts from index 0, second from index 2 and third from index 3.

Input: txt = "abba", pat = "aC"
Output: []
Explanation: There is no occurrence of "aC" in "abba".

[Naive Approach] Matching with all substrings

The idea is, we start at every index in the text and compare it with the first character of the pattern, if they match we move to the next character in both text and pattern. Also, before matching the characters, we can convert both the characters to lower case to ignore the case. If there is a mismatch, we start the same process for the next index of the text.


Output
0 3 

Time Complexity: O(n * m), where n is the length of txt and m is the length of pat.
Auxiliary Space: O(1)

[Expected Approach] Using KMP Algorithm

The idea is to use KMP Algorithm with the only modification to convert the characters to lowercase before comparing them during construction of lps[] array and while matching the characters.


Output
0 3 

Time Complexity: O(n + m), where is the length of the text and is the length of the pattern. This is because of creating the LPS (Longest Prefix Suffix) array takes O(m) time, and the search through the text takes O(n) time.

Auxiliary Space: O(m), as we need to store the LPS array of size m.

Comment
Article Tags:
Article Tags: