Anagram string c++

Problem

Write a C++ function that takes two strings of the same length as input and return true if the strings are anagrams otherwise returns false. Two strings are anagrams if they are permutations of each other ignoring spaces and capitalization. For example “CAT” and “ACT” are anagrams. Assume the input strings have small letter characters only.

Anagram string

Anagram string algorithm

This is a typical interview question. One solution is to sort each string then compare the sorted strings. If the sorted strings are identical then the input strings are anagrams otherwise they are not. We can borrow the merge sort code to sort the strings effectively in nlogn time then compare the strings in linear time. Another solution is compute unique character frequencies in each string. If the count is the same for each character then they are anagrams. We can use hash tables to efficiently compute character frequencies in each string.

Anagram string program code

Here is anagram strings example code in C++

Thanks for visiting. Please use the section below for questions or feedback.

Add a Comment

Your email address will not be published. Required fields are marked *