[Program] How to Check if Two Strings are Anagrams in C?

[Program] How to Check if Two Strings are Anagrams in C?

Before writing code to check if two strings are anagrams in C, let’s understand- what is the anagram of the string?

What is Anagram of the string?

An anagram of the string is the string, obtained by rearranging the letters of the source string.

Example:

Source String: csestack
Anagram of source String: cesstack

The second and third letters of the source string are altered, giving an anagram of the string.

Properties of Anagram String:

  • One string may have multiple anagrams.
  • Every string is anagram if itself.
  • If one string is the anagram of other string, both the strings have equal length. This is the first condition you should check for anagrams.

In C, you can check the length of the string using the strlen() function.

Program to Check if Two Strings are Anagrams in C

There are two approaches to check if the two strings are anagrams of each other or not.

1. by using Quick Sort

  • Sort the String using quicksort (both strings)
  • After sorting, check if two strings are identical or not
  • If two strings are identical then these two strings are anagrams of each other.
  • If not identical, these two strings are not anagrams of each other.
C

Output:

The two strings are an anagram of each other

For practice, you can solve the problem using any other popular sorting algorithms.

2. by counting each elements

  • Create two arrays of size 26 to save elements count for each letter
  • Scan first string and count number of times each unique element is repeated. Save count for each letter  in the first array
  • Repeat the same procedure for the second string.
  • Match the two array to check the count for each unique element.
  • If it is the same for both strings, two strings are an anagram of each other.
  • If there is a mismatch for any unique element count, these two strings are not an anagram of each other.
C

Output:

The two strings are anagram of each other.

This is one of the coding questions asked in the interview. If you are preparing for the job, practice solving these coding interview questions.

This is all about the program to check if two strings are anagrams in C. If you find any other better way of solving the same problem, let’s discuss it in the comment.

2 Comments

Leave a Reply

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