{"id":1535,"date":"2024-01-28T13:00:00","date_gmt":"2024-01-28T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1535"},"modified":"2024-01-30T06:38:37","modified_gmt":"2024-01-30T06:38:37","slug":"find-all-anagrams-string","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/find-all-anagrams-string\/","title":{"rendered":"Find all Anagrams in a String (C++, Java, Python)"},"content":{"rendered":"\n<p>Finding all anagrams in a string is one of the famous problems in Data structure that is often asked in technical interviews. In this article, we will understand this famous problem (also available in leetcode) and explore various approaches to solve it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Find all Anagrams in a String Problem<\/strong><\/h2>\n\n\n\n<p>First, let&#8217;s revise what an anagram is. An anagram is formed when the characters of one string can be rearranged to create another string. Take the words: &#8220;rama&#8221; and &#8220;amar&#8221;. The characters in &#8220;amar&#8221; can be rearranged to form &#8220;rama.&#8221;<\/p>\n\n\n\n<p><strong>In this problem we are given a string S and a pattern P, the task is to find the starting indices of substrings in S that are anagrams of P.<\/strong><\/p>\n\n\n\n<p>We will iterate through all possible substrings of S with the same length as P. For each substring, it checks whether the characters can be rearranged to match the characters in P. If a match is found, the starting index of that substring is added to the list of output indices. The final output is the list of starting indices where anagrams of P are present in S.<\/p>\n\n\n\n<p>Let us discuss it with an example:<\/p>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-1ba27e88ab95e5171c9a4203cb72d91b\" style=\"background-color:#fedcba\"><code>S = \"favavfvaf\"&nbsp;\nP = \"fav\"<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-5b22d4e147b54275742c0eb5b5c5a3ac\" style=\"background-color:#fedcba\"><code>&#91;0, 3, 5, 6]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Naive Approach: Using Sorting&nbsp;<\/strong><\/h2>\n\n\n\n<p>In this approach, we will use the concept of sorting the string.\u00a0Let us understand it better with an example:<\/p>\n\n\n\n<p>String P is &#8220;fav,&#8221; we can identify anagrams in string S by sorting both the pattern P and its potential anagrams. For instance, the anagrams of P in S are &#8220;fav,&#8221; &#8220;vfa,&#8221; and &#8220;afv.&#8221; When we sort P and its anagrams, they all become &#8220;fav.&#8221; This helps us to simplify the identification process.<\/p>\n\n\n\n<p><strong>To find anagrams of P in S, we can iterate through all substrings of S, sort each substring, and compare it to the sorted version of P. If they match, the substring is an anagram of P.<\/strong>\u00a0<\/p>\n\n\n\n<p>Firstly we will sort P and after sorting P becomes \u201cafv\u201d Then we will iterate over S with a Window equal to P\u2019s length.<\/p>\n\n\n\n<p>After taking that particular substring from the current window (let\u2019s say temp)&nbsp; we will sort it and if the sorted substring is equal to sorted P then we will push the starting index of the window to our answer array.<\/p>\n\n\n\n<p><strong>Sorted P<\/strong> = \u201cafv\u201d<\/p>\n\n\n\n<p><strong>Window size<\/strong> = 3<\/p>\n\n\n\n<p><strong>Current window substring<\/strong> = \u201cfav\u201d<\/p>\n\n\n\n<p><strong>Sorted substring<\/strong> = \u201cafv\u201d<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/ZVEvAQuJYc7mwM073PREDSgbtwrN0qTMFnQ8LMxL94FIWkXMxo2MS1sHdbBt2j9HE-a32xSgNxvCZ-5APqb59elV88dSuY_t6c3KASxvNNTezzhqUN6T8u5CSRjqnh4ZW0kIBFOEsTwt9Gl6bAuqyN8\" alt=\"Window of size 3\"\/><\/figure>\n<\/div>\n\n\n<p>Similarly, we will take all windows of size 3<\/p>\n\n\n\n<p>The Time Complexity of using sorting approach for finding all anagrams in a string is O(m log m) + O((n-m+1) * (m + m log m + m)). Because sorting string P takes O(m log m) time, where m is the length of string P and Iterating through all possible substrings of S: The for loop runs (n-m+1) times, where n is the length of string S.<\/p>\n\n\n\n<p>In each iteration, the algorithm builds a temporary substring (temp) of length m, sorts it (O(m log m)), and compares it with the sorted version of P (O(m)).<\/p>\n\n\n\n<p>The Space Complexity of this approach is O(m) because of the sorted string P and the temporary substring (temp) created in each iteration.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimized Approach: Hashing + Sliding Window<\/strong><\/h2>\n\n\n\n<p><strong>The best way to find all anagrams in a string is by using hashing with sliding windows.<\/strong> We will use <a href=\"https:\/\/favtutor.com\/blogs\/hashing-in-data-structure\">hashing<\/a> and <a href=\"https:\/\/favtutor.com\/blogs\/sliding-window-algorithm\">sliding windows<\/a> to identify anagrams of a given string P within string S, we can examine every substring of S that has the same length as P. To check an anagram we have to check that a substring contains the same character with the same frequency as those in P.\u00a0<\/p>\n\n\n\n<p>Below is the step-by-step guide to using hashing to find all anagrams:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>We will keep two arrays to track the frequencies of characters in both string P and the current substring in string S. If these frequency arrays match for a substring, then that substring is an anagram of string P.<\/li>\n\n\n\n<li>To identify substrings of the same length as string P we will maintain a window with a size equal to the length of string P.&nbsp;<\/li>\n\n\n\n<li>In each iteration, we will include a new character in the window while removing the first character. This ensures that the window length remains constant throughout each iteration.<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/fkTOHnano2_a7R93TiLS4zSrSq0sZghxFqS_P6RH1cf1Ek-87oLjp0Hw0R7m-KH8TksPkF0w8TUH5wU-25lKF3ITqX_vOm65Vb1AiLGQH0otwOuiGmOUb0Qjw9duIU8pOcHOeR04sMoBjsKjTIk_B9Y\" alt=\"Example\"\/><\/figure>\n<\/div>\n\n\n<p>Window size = Size of P = 3<br><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/m5M6HecCecfj0AR0zoUo3fRMyC-LEC4AWR1XT43IJaj6bHBfXjWt6i9ZhY7zmgdkeraXq-bfG9RCGmW5Oq5ELyR3lqE1w39G-WQXYKEBC1sOc9sfbV3wRj8G_l7cMhlxEp5_RkNPtzscmfvAhYFd7Vc\" alt=\"Hash Table of P\" style=\"width:288px;height:auto\"\/><\/figure>\n<\/div>\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/-EvhsYqa5Fbu3I267qxMH7pTfP55nHWAR91d_LML3qTZ5c38mNe6sbjPo4sOVtSlfwGtqqH0M9U3GM4BN3Sulf-TCeLEZHyeCsLrNojRM5cT7UysdldMsXDOZTOVWt85IfvcG3VGxLo-EEPoCubtHm8\" alt=\"Hash Table of current substring\" style=\"width:327px;height:auto\"\/><\/figure>\n<\/div>\n\n\n<p>The hash table of both the current window substring and the hash table of string P are the same.<\/p>\n\n\n\n<p>Hence both are anagrams.<\/p>\n\n\n\n<p>Similarly, take all windows of size 3.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the implementation in C++:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\n\/\/ Function to find starting indices of anagrams of string 'p' in string 's'\nvector&lt;int&gt; FindAnagrams(string &amp;s, string &amp;p)\n{\n    \/\/ Vector to store the starting indices of anagrams\n    vector&lt;int&gt; ans;\n\n    \/\/ Frequency arrays for characters in 'p' and the current window in 's'\n    vector&lt;int&gt; arr1(26, 0), arr2(26, 0);\n\n    \/\/ Lengths of strings 's' and 'p'\n    int n = s.length(), m = p.length();\n\n    \/\/ If 'p' is longer than 's', no anagrams are possible\n    if (m &gt; n)\n        return ans;\n\n    \/\/ Initialize the frequency arrays for the first window in 's'\n    for (int i = 0; i &lt; m; i++)\n        arr1[p[i] - 'a']++, arr2[s[i] - 'a']++;\n\n    \/\/ Check if the frequency arrays match for the first window\n    if (arr1 == arr2)\n        ans.push_back(0);\n\n    \/\/ Iterate through the remaining windows in 's'\n    for (int i = m; i &lt; n; i++)\n    {\n        \/\/ Include the new character in the current window\n        arr2[s[i] - 'a']++;\n\n        \/\/ Remove the first character from the window\n        arr2[s[i - m] - 'a']--;\n\n        \/\/ Check if the frequency arrays match for the current window\n        if (arr1 == arr2)\n            ans.push_back(i - m + 1);\n    }\n\n    return ans;\n}\n\n\/\/ Main function\nint main()\n{\n    \/\/ Example strings\n    string s = &quot;favavfvaf&quot;, p = &quot;fav&quot;;\n\n    \/\/ Find starting indices of anagrams\n    vector&lt;int&gt; arr = FindAnagrams(s, p);\n\n    \/\/ Display results\n    if (arr.empty())\n        cout &lt;&lt; &quot;There are No Anagrams of &quot; &lt;&lt; p &lt;&lt; &quot; in &quot; &lt;&lt; s &lt;&lt; endl;\n    else\n    {\n        cout &lt;&lt; &quot;Starting Indices of Anagrams are &quot; &lt;&lt; endl;\n        for (auto &amp;val : arr)\n            cout &lt;&lt; val &lt;&lt; &quot; &quot;;\n    }\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Find the Java code below to find all anagrams in a string:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\nclass fav{\n    \/\/ Function to find starting indices of anagrams of string 'p' in string 's'\n    static ArrayList&lt;Integer&gt; FindAnagrams(String s, String p) {\n        ArrayList&lt;Integer&gt; ans = new ArrayList&lt;&gt;();\n\n        \/\/ Frequency arrays for characters in 'p' and the current window in 's'\n        int[] arr1 = new int[26];\n        int[] arr2 = new int[26];\n        int n = s.length(), m = p.length();\n\n        \/\/ If 'p' is longer than 's', no anagrams are possible\n        if (m &gt; n)\n            return ans;\n\n        \/\/ Initialize the frequency arrays for the first window in 's'\n        for (int i = 0; i &lt; m; i++) {\n            arr1[p.charAt(i) - 'a']++;\n            arr2[s.charAt(i) - 'a']++;\n        }\n\n        \/\/ Check if the frequency arrays match for the first window\n        if (Arrays.equals(arr1, arr2))\n            ans.add(0);\n\n        \/\/ Iterate through the remaining windows in 's'\n        for (int i = m; i &lt; n; i++) {\n            \/\/ Include the new character in the current window\n            arr2[s.charAt(i) - 'a']++;\n\n            \/\/ Remove the first character from the window\n            arr2[s.charAt(i - m) - 'a']--;\n\n            \/\/ Check if the frequency arrays match for the current window\n            if (Arrays.equals(arr1, arr2))\n                ans.add(i - m + 1);\n        }\n\n        return ans;\n    }\n\n    \/\/ Main function\n    public static void main(String args[]) {\n        \/\/ Example strings\n        String s = &quot;favavfvaf&quot;, p = &quot;fav&quot;;\n\n        \/\/ Find starting indices of anagrams\n        ArrayList&lt;Integer&gt; arr = FindAnagrams(s, p);\n\n        \/\/ Display results\n        if (arr.isEmpty())\n            System.out.println(&quot;There are No Anagrams of &quot; + p + &quot; in &quot; + s);\n        else {\n            System.out.println(&quot;Starting Indices of Anagrams are &quot;);\n            for (int val : arr)\n                System.out.print(val + &quot; &quot;);\n        }\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Check the python program to solve this problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def find_anagrams(s, p):\n    ans = []\n    # Frequency arrays\n    arr1 = [0] * 26\n    arr2 = [0] * 26\n    n, m = len(s), len(p)\n\n    if m &gt; n:\n        return ans\n\n    # First window\n    for i in range(m):\n        arr1[ord(p[i]) - ord('a')] += 1\n        arr2[ord(s[i]) - ord('a')] += 1\n\n    if arr1 == arr2:\n        ans.append(0)\n\n    # Subsequent windows\n    for i in range(m, n):\n        arr2[ord(s[i]) - ord('a')] += 1\n        arr2[ord(s[i - m]) - ord('a')] -= 1\n\n        if arr1 == arr2:\n            ans.append(i - m + 1)\n\n    return ans\n\n# Main function\ndef main():\n    s = &quot;favavfvaf&quot;\n    p = &quot;fav&quot;\n    arr = find_anagrams(s, p)\n\n    if not arr:\n        print(f&quot;There are No Anagrams of {p} in {s}&quot;)\n    else:\n        print(&quot;Starting Indices of Anagrams are:&quot;)\n        print(*arr)\n\nif __name__ == &quot;__main__&quot;:\n    main()<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-ca1997c75e48b93a7f4f27b861c1d11f\" style=\"background-color:#fedcba\"><code>Starting Indices of Anagrams are \n0 3 5 6 <\/code><\/pre>\n\n\n\n<p>The Time Complexity to find all anagrams in a string using hashing and sliding windows is O((n-m+1)*26), because for loop iterates for &#8220;n &#8211; m + 1&#8221; times, representing the possible starting positions of substrings of length equal to string P within string S. <\/p>\n\n\n\n<p>In each iteration, the frequency arrays of the current substring in string S and string P are compared. The Space Complexity of this optimized approach is O(1).<\/p>\n\n\n\n<p>Here is the comparison of both approaches:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Approaches<\/strong><\/td><td><strong>Time Complexity<\/strong><\/td><td><strong>Space Complexity<\/strong><\/td><td><strong>Details\u00a0<\/strong><\/td><\/tr><tr><td>Naive approach: Sorting<\/td><td>O(mlogm) + O( (n-m+1)*(m+mlogm+m) )&nbsp;<\/td><td>O(n*m)&nbsp;<\/td><td>We take substrings from the window of size equal to the size of P and compare the sorted substrings with sorted P. If they are equal then they are anagrams.<\/td><\/tr><tr><td>Hashing + Sliding Window<\/td><td>O((n-m+1)*26)&nbsp;<\/td><td>O(1)<\/td><td>We take substrings from the window of size equal to the size of P and compare the hash table of characters substring with the hash table of P. If they are equal then they are anagrams.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In conclusion, the optimized Hashing + Sliding Window approach stands out as the most efficient solution for finding all anagrams in a string problem. This approach is recommended for larger datasets.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Finding all anagrams in a string is one of the famous problems in Data structure that is often asked in technical interviews. In this article, we will understand this famous problem (also available in leetcode) and explore various approaches to solve it. Find all Anagrams in a String Problem First, let&#8217;s revise what an anagram [&hellip;]<\/p>\n","protected":false},"author":12,"featured_media":1537,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1535","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1535","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1535"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1535\/revisions"}],"predecessor-version":[{"id":1588,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1535\/revisions\/1588"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1537"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1535"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1535"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1535"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}