Valid Anagram

Easy C++ Kotlin

Problem Statement

Given two strings s and t , write a function to determine if t is an anagram of s.

Questions to ask

Characters in the string are only lowercase? Yes

Can special characters exist in the string? No

Solution

The solution is pretty straightforward. Knowing that the a character is a number from 0 to 255, make an array to count the frequency of characters from the first string. Now you will loop trough the second array and remove the character from the array that count the frequency. Loop through the frequency array and if some value is different from 0 return false. Otherwise return true when the loop finish.

bool isAnagram(string s, string t){
  vector<int> counter (26,0);

  for(auto letter : s){
    counter[letter-'a']++;
  }

  for(auto letter : t){
    counter[letter-'a']--;
  }

  for(auto count : counter){
    if(count!=0)
      return false;
  }

  return true;
}

Time Complexity: O(n)

Space Complexity: O(1)


question from LeetCode