242. Valid Anagram LeetCode Solution

In this guide, you will get 242. Valid Anagram LeetCode Solution with the best time and space complexity. The solution to Valid Anagram problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Valid Anagram solution in C++
  4. Valid Anagram solution in Java
  5. Valid Anagram solution in Python
  6. Additional Resources
242. Valid Anagram LeetCode Solution image

Problem Statement of Valid Anagram

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example 1:

Input: s = “anagram”, t = “nagaram”
Output: true

Example 2:

Input: s = “rat”, t = “car”
Output: false

Constraints:

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(26) = O(1)

242. Valid Anagram LeetCode Solution in C++

class Solution {
 public:
  bool isAnagram(string s, string t) {
    if (s.length() != t.length())
      return false;

    vector<int> count(26);

    for (const char c : s)
      ++count[c - 'a'];

    for (const char c : t) {
      if (count[c - 'a'] == 0)
        return false;
      --count[c - 'a'];
    }

    return true;
  }
};
/* code provided by PROGIEZ */

242. Valid Anagram LeetCode Solution in Java

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

    int[] count = new int[26];

    for (final char c : s.toCharArray())
      ++count[c - 'a'];

    for (final char c : t.toCharArray()) {
      if (count[c - 'a'] == 0)
        return false;
      --count[c - 'a'];
    }

    return true;
  }
}
// code provided by PROGIEZ

242. Valid Anagram LeetCode Solution in Python

class Solution:
  def isAnagram(self, s: str, t: str) -> bool:
    if len(s) != len(t):
      return False

    count = collections.Counter(s)
    count.subtract(collections.Counter(t))
    return all(freq == 0 for freq in count.values())
# code by PROGIEZ

Additional Resources

See also  775. Global and Local Inversions LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.