Java program to check if two strings are anagrams

Carvia Tech | May 18, 2019 | 2 min read | 351 views | Java Coding Challenges


Anagram

Two strings are called anagrams if they contain same set of characters but in different order. For example,

  • peek and keep are anagrams

  • spar and rasp are anagrams

  • listen and silent are anagrams

Approach 1: sorting of characters

  1. Sort characters within string for both the inputs.

  2. if the two strings are same after sorting, they are anagram else not.

Let’s write Java code that takes this approach and checks if two given inputs are anagrams or not.

AnagramChecker.java
import java.util.Arrays;

public class AnagramChecker {

    public boolean isAnagram(String input1, String input2) {
        char[] sortedWord1 = input1.toCharArray();
        Arrays.sort(sortedWord1);

        char[] sortedWord2 = input2.toCharArray();
        Arrays.sort(sortedWord2);

        return Arrays.equals(sortedWord1, sortedWord2);
    }
}

Here is the unit test for above method.

JUnit testcase
import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;

public class AnagramCheckerTest {

    @Test
    public void isAnagram() {
        AnagramChecker checker = new AnagramChecker();

        assertThat(checker.isAnagram("peek", "keep"), equalTo(true));
        assertThat(checker.isAnagram("mary", "army"), equalTo(true));

        assertThat(checker.isAnagram("dart", "mart"), equalTo(false));
    }
}

Approach 2: Using count of characters for both words and compare

Alternatively, we can count the number of characters in both words and compare it for exactness. This approach is slightly efficient, as it has time complexity of Big O(n) compared to Big O(n log n) in earlier case.

AnagramEfficient.java
public class AnagramEfficient {

    public boolean isAnagram(String first, String second) {
        int[] letterCount = new int[126];

        for (char ch : first.toCharArray()) {
            letterCount[ch]++;
        }

        for (char ch : second.toCharArray()) {
            letterCount[ch]--;
        }

        for (int count : letterCount) {
            if (count != 0)
                return false;
        }
        return true;
    }
}

Here we are assuming that input is always an ASCII text without unicode support.

We can lowercase the input in both the approaches to make it case-insensitive.


Java Coding Challenges:
  1. Check if the given number is Armstrong Number in Java
  2. Create anagram buckets from a given input array of words
  3. Find two numbers of which the product is maximum in an array
  4. Check if the given string is palindrome
  5. Check a number is Prime: Java Coding Problem
  6. How will you check if a given sentence is a pangram
  7. How to reverse a number in Java
See all articles in Java Coding Challenges
Top articles in this category:
  1. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: Rest Assured Interview Questions
  3. SDET: JUnit interview questions for automation engineer
  4. Write a program to reverse a string using recursion in Java
  5. Check if the given string is palindrome
  6. How will you compare two java objects
  7. Check whether given number is even or odd



Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info