C Program
#include <stdio.h> #include <string.h> #include <stdlib.h> // Function to sort characters in a string void sortString(char *str) { int n = strlen(str); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (str[i] > str[j]) { char temp = str[i]; str[i] = str[j]; str[j] = temp; } } } } int main() { char words[5][20] = {"cat", "dog", "tac", "god", "act"}; int used[5] = {0}; printf("Grouped Anagrams:\n"); for (int i = 0; i < 5; i++) { if (used[i]) continue; char sorted[20]; strcpy(sorted, words[i]); sortString(sorted); printf("{ "); for (int j = i; j < 5; j++) { char temp[20]; strcpy(temp, words[j]); sortString(temp); if (strcmp(sorted, temp) == 0) { printf("%s ", words[j]); used[j] = 1; } } printf("}\n"); } return 0; }
C Output
Grouped Anagrams: { cat tac act } { dog god }
C++ Program
#include <iostream> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; int main() { vector<string> words = {"cat", "dog", "tac", "god", "act"}; unordered_map<string, vector<string>> groups; for (string word : words) { string sorted = word; sort(sorted.begin(), sorted.end()); groups[sorted].push_back(word); } cout << "Grouped Anagrams:\n"; for (auto &group : groups) { cout << "{ "; for (string w : group.second) cout << w << " "; cout << "}\n"; } return 0; }
C++ Output
Grouped Anagrams: { cat tac act } { dog god }
JAVA Program
import java.util.*; public class Main { public static void main(String[] args) { String[] words = {"cat", "dog", "tac", "god", "act"}; Map<String, List<String>> groups = new HashMap<>(); for (String word : words) { char[] arr = word.toCharArray(); Arrays.sort(arr); String key = new String(arr); groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word); } System.out.println("Grouped Anagrams:"); for (List<String> group : groups.values()) { System.out.println(group); } } }
JAVA Output
Grouped Anagrams: [cat, tac, act] [dog, god]
Python Program
from collections import defaultdict words = ["cat", "dog", "tac", "god", "act"] groups = defaultdict(list) for word in words: key = "".join(sorted(word)) groups[key].append(word) print("Grouped Anagrams:") for group in groups.values(): print(group)
Python Output
Grouped Anagrams: ['cat', 'tac', 'act'] ['dog', 'god']
Deep Explanation
Example
Consider the words: ["cat", "dog", "tac", "god", "act"].
Sorting the letters in "cat" gives us "act". Sorting "tac" or "act" also results in "act". This is their signature, which informs us that they fit into the same category. The words "dog" and "god" have "dgo" as their signature, so they belong to another category.
Real-Life Analogy
Consider anagrams to be different shufflings of the same letters. When two players shuffle the same cards, though the sequence is different, the cards remain the same. In the same way, anagrams are different shuffles of the same letters. Clustering them means placing all shuffled ones into the same container.
Why It Matters
Grouping anagrams isn't only an entertaining puzzle—it is an exercise in hashing and classification. In the real world, search engines classify words with the same root letter, plagiarism detectors discover rearranged words, and spell-checkers offer suggestions by matching sorted letter patterns. This problem is a building block for data classification, and that is very important in natural language processing and artificial intelligence.
Learning Insights
You learn to utilize maps/dictionaries to build groups dynamically. Using a sorted form of a word as a key, you immediately identify all anagrams. This develops intuition for hashing, key-value mapping, and lookups. Novices gain an experiential sense of how efficient dictionaries or hash maps are in solving such issues.
Interview Relevance
This is a traditional coding interview question posed by recruiters such as Google, Amazon, and Microsoft. It represents knowledge of string manipulation, hashing, and data structure. The interviewer wishes to establish whether you are able to optimize past brute-force comparisons using hashing with sorted signatures.
Real-World Application
This reasoning applies to issues such as DNA sequencing (clustering sequences that are permutations of one another), cryptography (identifying jumbled cipher text), and text processing (identifying word families). It's a small idea but has uses in the realms of AI, cyber security, and linguistics.
SEO-Optimized Closing Paragraph
It's one of the most crucial string manipulation issues in computer programming to learn how to cluster anagrams with C, C++, Java, and Python. This issue not just enhances logical reasoning but also assists you in practicing maps, hash tables, and sorting in coding interviews. Solved by solving the group anagrams problem using various programming languages, you establish robust concepts in algorithms and data structures as you prepare for real-world uses in text processing, natural language processing, as well as bioinformatics. If you are doing coding interview preparations or competitive programming, learning the group anagrams solution will put you in a good position.
Social Plugin