• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
October 31, 2022 |2.4K Views

Java Program to Check if Two Strings are Anagrams

Description
Discussion

In this video, we will write a Java Program to Check if Two Strings are Anagrams.

What are anagrams?
Anagrams are words or phrases you spell by rearranging the letters of another word or phrase.

For examples:
String 1: abac
String 2: abca
Output: True

String 1: act
String 2: cat
Output: True

Here in this video, we cover two different methods to check it:

1. Using the Brute force method:

Here we sort both strings and compare the sorted strings.
Step 1: Make the character array of strings.
Step 2: Sort both the character array.
Step 3: Now check character array 1 and character array 2, if both are equal then print both strings are anagrams otherwise print false.

2. Using Optimized Method:

Step 1: In this method, two arrays are used.
Step 2: Iterate through every character of both strings and increment the count of characters in the corresponding count arrays using for loop.
Step 3: Compare count arrays. If both the count arrays are the same, then it returns true, otherwise, print false.

Apart from that, we will see the time and space complexity of both mentioned methods i.e:

For brute force method:
Time complexity: O(n*logN)
Space complexity: O(1)

For Optimized method:
Time complexity: O(n)
Space complexity: O(n)