Anagram Substring Search (Or Search for all permutations)
Last Updated :
23 Jul, 2025
Given a text txt and a pattern pat of size n and m respectively, the task is to find all occurrences of pat and its permutations (or anagrams) in txt. You may assume n > m.
Examples:
Input: txt = "BACDGABCDA", pat = "ABCD"
Output: [0, 5, 6]
Explanation: "BACD" is at 0, "ABCD" at 5 and "BCDA" at 6
Input: txt = "AAABABAA", pat = "AABA"
Output: [0, 1, 4]
Explanation: "AAAB" is at 0, "AABA" at 5 and "ABAA" at 6
Naive Solution - O((m log m) + (n-m+1)(m log m) ) Time & O(m) Space
This problem is slightly different from the standard pattern-searching problem, here we need to search for anagrams as well. Therefore, we cannot directly apply standard pattern-searching algorithms like KMP, Rabin Karp, Boyer Moore, etc.
The idea is to consider all the substrings of the txt with are of lengths equal to the length of pat and check whether the sorted version of substring is equal to the sorted version of pat. If they are equal then that particular substring is the permutation of the pat, else not.
Illustration:
Text (txt): "BACABC", Pattern (pat): "CBA"
- Sort pat to get sortedpat = "ABC".
- For each substring in txt of length equal to pat (length 3):
- Substring "BAC": Sort to get "ABC" (match found, add index 0).
- Substring "ACA": Sort to get "AAC" (no match).
- Substring "CAB": Sort to get "ABC" (match found, add index 2).
- Substring "ABC": Sort to get "ABC" (match found, add index 3).
The indices of anagrams found are 0, 2, and 3.
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> search(string& pat, string& txt) {
int n = txt.length(), m = pat.length();
/* sortedpat stores the sorted version of pat */
string sortedpat = pat;
sort(sortedpat.begin(), sortedpat.end());
// to store the matching indices
vector<int> res;
for (int i = 0; i <= n - m; i++) {
// renamed from temp to curr
string curr = "";
for (int k = i; k < m + i; k++)
curr.push_back(txt[k]);
sort(curr.begin(), curr.end());
/* checking if sorted versions are equal */
if (sortedpat == curr)
res.push_back(i);
}
return res;
}
int main() {
string txt = "BACDGABCDA";
string pat = "ABCD";
vector<int> result = search(pat, txt);
for (int idx : result)
cout << idx << " ";
return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to sort characters in a string
void sortString(char* str, int len) {
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (str[i] > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
// Function to search for anagrams of the pattern in text
void search(char* pat, char* txt, int* result, int* resCount) {
int n = strlen(txt);
int m = strlen(pat);
//sortedpat stores the sorted version of pat
char sortedpat[m + 1];
strcpy(sortedpat, pat);
sortString(sortedpat, m);
*resCount = 0;
for (int i = 0; i <= n - m; i++) {
// renamed from temp to curr
char curr[m + 1];
strncpy(curr, txt + i, m);
curr[m] = '\0';
sortString(curr, m);
//checking if sorted versions are equal
if (strcmp(sortedpat, curr) == 0) {
result[*resCount] = i;
(*resCount)++;
}
}
}
// Driver code
int main() {
char txt[] = "BACDGABCDA";
char pat[] = "ABCD";
int result[100], resCount;
search(pat, txt, result, &resCount);
for (int i = 0; i < resCount; i++) {
printf("%d ", result[i]);
}
return 0;
}
Java
import java.util.*;
class GfG {
// Function to search for anagrams of the pattern in text
static List<Integer> search(String pat, String txt) {
int n = txt.length(), m = pat.length();
//sortedpat stores the sorted version of pat
char[] sortedpatArr = pat.toCharArray();
Arrays.sort(sortedpatArr);
String sortedpat = new String(sortedpatArr);
// to store the matching indices
List<Integer> res = new ArrayList<>();
for (int i = 0; i <= n - m; i++) {
// renamed from temp to curr
String curr = txt.substring(i, i + m);
char[] currArr = curr.toCharArray();
Arrays.sort(currArr);
curr = new String(currArr);
//checking if sorted versions are equal
if (sortedpat.equals(curr)) {
res.add(i);
}
}
return res;
}
// Driver code
public static void main(String[] args) {
String txt = "BACDGABCDA";
String pat = "ABCD";
List<Integer> result = search(pat, txt);
for (int idx : result) {
System.out.print(idx + " ");
}
}
}
Python
# Function to search for anagrams of the pattern in text
def search(pat, txt):
n = len(txt)
m = len(pat)
# sortedpat stores the sorted version of pat
sortedpat = ''.join(sorted(pat))
# to store the matching indices
res = []
for i in range(n - m + 1):
# renamed from temp to curr
curr = txt[i:i + m]
curr = ''.join(sorted(curr))
# checking if sorted versions are equal
if sortedpat == curr:
res.append(i)
return res
# Driver code
txt = "BACDGABCDA"
pat = "ABCD"
result = search(pat, txt)
for idx in result:
print(idx, end=" ")
C#
using System;
using System.Collections.Generic;
class GfG
{
static List<int> Search(string pat, string txt)
{
int n = txt.Length, m = pat.Length;
/* sortedpat stores the sorted version of pat */
char[] sortedPatArr = pat.ToCharArray();
Array.Sort(sortedPatArr);
string sortedPat = new string(sortedPatArr);
// to store the matching indices
List<int> res = new List<int>();
for (int i = 0; i <= n - m; i++)
{
// renamed from temp to curr
string curr = "";
for (int k = i; k < m + i; k++)
curr += txt[k];
char[] currArr = curr.ToCharArray();
Array.Sort(currArr);
string sortedCurr = new string(currArr);
/* checking if sorted versions are equal */
if (sortedPat == sortedCurr)
res.Add(i);
}
return res;
}
static void Main(string[] args)
{
string txt = "BACDGABCDA";
string pat = "ABCD";
List<int> result = Search(pat, txt);
foreach (int idx in result)
Console.Write(idx + " ");
Console.ReadLine();
}
}
JavaScript
// Function to search for anagrams of the pattern in text
function search(pat, txt) {
const n = txt.length, m = pat.length;
// sortedpat stores the sorted version of pat
const sortedpat = pat.split('').sort().join('');
// to store the matching indices
const res = [];
for (let i = 0; i <= n - m; i++) {
// renamed from temp to curr
let curr = txt.slice(i, i + m).split('').sort().join('');
// checking if sorted versions are equal
if (sortedpat === curr) {
res.push(i);
}
}
return res;
}
// Driver code
const txt = "BACDGABCDA";
const pat = "ABCD";
const result = search(pat, txt);
console.log(result.join(" "));
Time Complexity: The for loop runs for n-m+1 times in each iteration we build a string of size m, which takes O(m) time, and sorting it takes O(m log m) time, and comparing sorted pat and sorted substring, which takes O(m). So time complexity is O((n-m+1)*(m + m log m + m) ). Total Time is O(m log m) + O( (n-m+1)(m + mlogm + m) )
Auxiliary Space: O(m) As we are using extra space for curr string and sorted pat
Hashing and Window Sliding - O(256 * (n - m) + m) Time & O(m + 256) Space
Instead of checking each substring one by one like we were doing in the above naive approach, we can use two arrays to count how many times each character appears in the pattern and in the current part/window of the text we're looking at. By sliding this window across the text and updating our counts, we can quickly determine if the current substring matches the pattern. This method is much faster and allows us to handle larger texts more efficiently.
For more detail about the implementation part, please refer to this article
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem