Valid Anagram

Problem Statement

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

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

Approach 1: Sorting

Explanation: Sort both strings and compare.

Time Complexity: O(n log n)

Space Complexity: O(1) or O(n) depending on sorting implementation

if sort(s) == sort(t):
    return true
else:
    return false
      
Heap Sort Flowchart

Approach 2: Hash Map Frequency Count

Explanation: Count frequency of each character in s and t, then compare.

Time Complexity: O(n)

Space Complexity: O(n)

count_s = {}
count_t = {}
for char in s:
    count_s[char]++
for char in t:
    count_t[char]++
return count_s == count_t
      
Heap Sort Flowchart

Approach 3: Single Hash Map (Optimal)

Explanation: Count chars in s, decrement with t, check if all counts zero.

Time Complexity: O(n)

Space Complexity: O(n)

count = {}
for char in s:
    count[char]++
for char in t:
    if char not in count:
        return false
    count[char]--
for val in count.values():
    if val != 0:
        return false
return true
      
Heap Sort Flowchart