Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
Check If Two Strings Are Anagrams

Check If Two Strings Are Anagrams

Problem Statement

You’re a word rearranger with two strings. Do they contain the same letters in any order? This easy-level hashing task is a twin to Valid Anagram—a quick check to see if they’re scrambled siblings!

Example

Input: s = "listen", t = "silent"

Output: true (Same letters)

Input: s = "hello", t = "world"

Output: false (Different letters)

Input: s = "", t = ""

Output: true (Empty anagrams)

Code

Java
Python
JavaScript
public class Solution {
    public boolean areAnagrams(String s, String t) {
        if (s.length() != t.length()) return false;
        int[] count = new int[26];
        for (char c : s.toCharArray()) count[c - 'a']++;
        for (char c : t.toCharArray()) count[c - 'a']--;
        for (int val : count) if (val != 0) return false;
        return true;
    }
}
            
def are_anagrams(s, t):
    return sorted(s) == sorted(t)
            
function areAnagrams(s, t) {
    if (s.length !== t.length) return false;
    return s.split('').sort().join('') === t.split('').sort().join('');
}
            

Explanation

  • Hashing Insight: Compare char counts or sorted strings for equality.
  • Flow: Sort both strings and compare (simple), or use a freq array (faster).
  • Example Walkthrough: "listen","silent" → "eilnst" vs "eilnst" → true.
  • Java Optimization: Array[26] for lowercase letters beats sorting.
  • Edge Case: Empty strings or diff lengths handled upfront.

Note

Time complexity: O(n log n) with sorting, O(n) with array; Space: O(1) or O(n). A quick anagram check with hashing charm!