DEV Community

Sharmila devi
Sharmila devi

Posted on

# 🔤 Valid Anagram in Java – Efficient Ways to Solve It

Checking whether two strings are anagrams is a very common problem in coding interviews and real-world applications. It tests your understanding of strings, hashing, and sorting techniques.

In this blog, we’ll explore what anagrams are and how to solve the problem efficiently in Java.


🚀 Problem Statement

Given two strings s and t, return:

  • true → if t is an anagram of s
  • false → otherwise

🤔 What is an Anagram?

Two strings are called anagrams if:

  • They contain the same characters
  • With the same frequency
  • But possibly in a different order

👉 Examples

```java id="eg1"
Input: s = "anagram", t = "nagaram"
Output: true






```java id="eg2"
Input:  s = "rat", t = "car"
Output: false
Enter fullscreen mode Exit fullscreen mode

💡 Key Insight

To determine if two strings are anagrams:

  • The length must be the same
  • The frequency of each character must match

⚡ Approach 1: Character Frequency Count (Optimal)

🧠 Idea

  • Count characters in string s
  • Subtract counts using string t
  • If all counts become zero → anagram

🧑‍💻 Java Implementation

```java id="code1"
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;

    int[] count = new int[26]; // assuming lowercase letters

    // Count characters from s
    for (char c : s.toCharArray()) {
        count[c - 'a']++;
    }

    // Subtract using t
    for (char c : t.toCharArray()) {
        count[c - 'a']--;
    }

    // Check if all counts are zero
    for (int num : count) {
        if (num != 0) return false;
    }

    return true;
}
Enter fullscreen mode Exit fullscreen mode

}




---

## ⏱️ Complexity Analysis

| Aspect | Complexity |
| ------ | ---------- |
| Time   | O(n)       |
| Space  | O(1)       |

✔ Constant space because array size is fixed (26 letters)

---

# 🔄 Approach 2: Sorting

## 🧠 Idea

* Convert both strings to character arrays
* Sort them
* Compare results

---

## 🧑‍💻 Java Implementation



```java id="code2"
import java.util.Arrays;

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

        char[] arr1 = s.toCharArray();
        char[] arr2 = t.toCharArray();

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        return Arrays.equals(arr1, arr2);
    }
}
Enter fullscreen mode Exit fullscreen mode

⏱️ Complexity

Aspect Complexity
Time O(n log n)
Space O(n)

⚖️ Comparison of Approaches

Method Time Complexity Space Best For
Frequency Count O(n) O(1) Optimal solution
Sorting O(n log n) O(n) Simpler logic

⚠️ Common Mistakes

  • ❌ Not checking string lengths first
  • ❌ Assuming only lowercase letters (when not specified)
  • ❌ Using inefficient nested loops (O(n²))

🎯 When to Use Which?

  • Use frequency count when:

    • You want optimal performance
    • Input is limited to lowercase letters
  • Use sorting when:

    • Simplicity matters more than performance
    • Character set is large or unknown

🏁 Conclusion

The anagram problem is simple yet powerful:

  • It teaches frequency counting
  • Reinforces string manipulation skills
  • Appears frequently in coding interviews

Mastering both approaches will give you flexibility in solving similar problems.

Top comments (0)