◻️242. Valid Anagram (easy)

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Solutions

Brute Force

  • Sort the two strings

  • Compare

  • If equal then anagram.

T.C -> O(n log n)

Optimised

Runtime 4 ms Memory 8.89 MB

Bucket System

Determine if two strings/phrases are valid Anagrams | Study Algorithms
Nikhil Lohia
  • Create empty bucket for 26 alphabets

  • for each s[i]-'a' increase the count +1

  • then for each t[i]-'a' decrease the count -1

  • compare if the bucket has all elements equal to 0

Last updated