✅Simple & Easy w/ explanation | Counting Mismatches O(N)
Solution-I\n\nWe just need to verify if both the strings contains characters with same frequency and then, the number of mismatch is either 0 or 2 (1 wont be po
***Solution-I***\n\nWe just need to verify if both the strings contains characters with same frequency and then, the number of mismatch is either `0` or `2` (`1` wont be possible since all character frequency is same is verified first).\n\n```\nbool areAlmostEqual(string s1, string s2) {\n\tint n = size(s1), mismatch=0, flag = 1;\n\tvector<int>arr(26);\n\tfor(int i = 0; i < n; i++)\n\t\tarr[s1[i] - \'a\']++, arr[s2[i] - \'a\']--;        \n\tfor(auto freqDiff : arr)\n\t\tif(freqDiff){     // if frequency difference of characters in both strings is different\n\t\t\tflag = 0; break;\n\t\t}\n\tif(!flag) return false;\n\n\tfor(int i = 0; i < n; i++)\n\t\tif(s1[i] != s2[i])\n\t\t\tmismatch++;\n\treturn mismatch <= 2;\n}\n```\n**Time Complexity :** **`O(N)`**, for iterating over the array.\n**Space Complexity :** **`O(1)`**, since only constant space is used.\n\n\n----------\n-----------\n\n***Solution-II (Optimized)***\n\nInfact, we dont really need to count and store the frequency as we did in the first step. As already mentioned above, the count of mismatch will be `0` or `2` for *almostEqual* strings. We just need to verify that in case of mismatch equal to 2, the mismatched characters in at first index in `s1` needs to be same as mismatched character at other index in `s2`. \n\n```\nbool areAlmostEqual(string s1, string s2) {\n\tint n = size(s1), cnt=0, idx1=0, idx2=0;\n\tfor(int i = 0; i < n; i++)\n\t\tif(s1[i] != s2[i]){\n\t\t\tcnt++;\n\t\t\tif(!idx1) idx1 = i; else idx2 = i;\n\t\t}             \n\treturn (cnt == 0 || cnt == 2) && s1[idx1] == s2[idx2] && s1[idx2] == s2[idx1];\n}\n```\n\n**Time Complexity :** **`O(N)`**, for iterating over the array.\n**Space Complexity :** **`O(1)`**, since only constant space is used. The constant factor here is much lesser as compared to *solution-I*.
['C']