Make Selenium Easy

Frequently Asked Java Programs: 34 – Java Program to Check if Two Strings are Anagram

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to check if two given strings are anagram.

What are Anagrams strings?

Two words are called Anagrams if they have the same characters with same number of occurance.

For example:- SILENT and LISTEN are anagrams.

We can also say an anagram is a word which can be formed by rearranging all characters of another word in same count.

Problem statement:-

Write a Java program to find two given case insensitive strings are anagram or not .

Solution:-

In fact there are many ways to do above program. Some logics are:-

  1. Sort both strings and check for equal. It is more optimal.
  2. Count occurence of each char in both strings and compare. Continue if counts are same else break.
  3. Iterate char by char and delete/replace character and get length. Break as soon as lengths are different.

But in interview, you are asked to write without using any direct readymade methods. So I will explain two ways here.

Approach 1: – Sort and check equal

As per definition of Anagram above, you can conclude now that two strings should be of equal size and equal sorting order to be anagram.

Logic:-

  1. Compare the length of both strings. If same then go for step 2 otherwise exit as there is no chances to be anagram strings.
  2. Convert both given string to same case.
  3. Sort both strings.
  4. Check equality of both strings. If same, both strings will be anagrams.

Output:-

Approach 2: – Iteration

Logic:-

  1. Compare the length of both strings. If same then go for step 2 otherwise exit as there is no chances to be anagram strings.
  2. Iterate any one string char by char.
  3. Check presence of char in another string. If not present exit else go to step 4.
  4. Remove all occurance of checked char from both strings.

Output:-

#HappyCoding

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.