Check if two Strings are Anagrams of each other

Program for checking if two strings are Anagram of each other – Is Anagram?

Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.

An anagram is a word or phrase that can be rearranged to form another word or phrase by using all the original letters exactly once. For example, “listen” and “silent” are anagrams because they have the same letters, even though they are arranged differently.

Is Anagram

Note s and t consist of lowercase English letters.

Program for checking if two strings are Anagram of each other - Is Anagram Solution

Recommendation – To check if two strings are anagrams, ensure they have the same length and identical character counts; if both conditions are met, they are anagrams.

There are mainly 2 approach to solve this problem –

  1. Sorting Method
  2. Hash Table Method
    • Non-Optimal method
    • Optimal method

1. Sorting Method

This method sort both strings alphabetically and check if they match. If they are identical after sorting, the strings are anagrams. This method is straightforward but may be slower for long strings.

  • Time complexity: O(nlogn)
  • Space complexity: O(1) or O(n) depending on the sorting algorithm.

Code

2. Hash Table Method

This method Count the occurrences of each character in both strings using a hash table (or dictionary). Then, compare these counts. If they’re the same, the strings are anagrams. This approach is faster and more efficient, especially for large strings.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code(Non-Optimal)

Code(Optimal)

  • Time complexity: O(n)
  • Space complexity: O(1)

More Articles