Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Valid Anagram problem solution

YASH PAL, 31 July 2024

In this Leetcode Valid Anagram problem solution we have given two strings s and t, return true if t is an anagram of s, and false otherwise.

Leetcode Valid Anagram problem solution

Problem solution in Python.

from collections import Counter
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return Counter(s) == Counter(t)

Problem solution in Java.

public boolean isAnagram(String s, String t) {
    int len1=s.length(),len2=t.length();
    if(s==null||t==null||len1!=len2)
      return false;
      HashMap<Character,Integer> map=new HashMap<Character,Integer>();
      for(int i=0;i<len1;i++){
          char c=s.charAt(i);
          if(map.get(c)==null)
            map.put(c,1);
          else
            map.put(c,map.get(c)+1);
      }
      
      for(int i=0;i<len2;i++){
          char c=t.charAt(i);
          if(map.get(c)==null)
            return false;
          else{
            int num=map.get(c);
            if(num==0)
              return false;
            else
              map.put(c,map.get(c)-1);
          }
      }
      
     return true;
}

Problem solution in C++.

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size()!=t.size()) return false;
        int count[26]={0};
        for(int i=0;i<s.size();i++) 
            count[s[i]-'a']++;
        for(int i=0;i<s.size();i++){
            count[t[i]-'a']--;
            if(count[t[i]-'a']<0) return false;
        }
        return true;
    }
};

Problem solution in C.

bool isAnagram(char * s, char * t){ 
    unsigned long long s1 = 0, s2 = 0, p1 = 1, p2 = 1;  
    for (; *s && *t ; s1 += *s, s2 += *t, p1 *= *s++, p2 *= *t++);
    return !*s && !*t && s1 == s2 && p1 == p2;
}

coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes