
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Pairs of Anagrams in a Given Array of Strings in C++
In this problem, we are given an array of strings and we have to print all pairs of anagrams of that given array.
Anagrams are strings that are formed by rearranging the character of another string. Like − hello and lolhe
Let’s take an example to understand the problem −
Input: array = {“hello”, “hrdef”, “from”, “lohel”, “morf”}. Output: [hello, lohel] , [from , morf]
To solve this problem, we will use the nesting of loops. We need two nested loops, the outer loop will traverse over the array and select elements. The nested loop will check each of the string and check if they are anagrams or not.
Example
Let’s see the program to implement that algorithm −
#include <iostream> using namespace std; #define NO_OF_CHARS 256 bool isAnagramString(string str1, string str2){ int count[NO_OF_CHARS] = {0}; int i; for (i = 0; str1[i] && str2[i]; i++){ count[str1[i]]++; count[str2[i]]--; } if (str1[i] || str2[i]) return false; for (i = 0; i < NO_OF_CHARS; i++) if (count[i]) return false; return true; } void printAnagrams(string arr[], int n){ for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (isAnagramString(arr[i], arr[j])) cout<<arr[i]<<" and "<<arr[j]<<" are anagrams.\n"; } int main(){ string arr[] = {"hello", "hrdef", "from", "lohel", "morf"}; int n = sizeof(arr)/sizeof(arr[0]); printAnagrams(arr, n); return 0; }
Output
hello and lohel are anagrams. from and morf are anagrams.
This solution is quite easy to understand but is less efficient. So there can be some optimizations that can be made to our solutions to make it more effective. We can do it by sorting our array that contains a string. This sorted array will make anagram find easier.