Back to Dashboard

Valid Anagram

Easy

Problem Statement

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, using all the original letters exactly once.

Examples

Example 1:

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

Approach 1 HashMap:

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        var hMap = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i ++) {
            hMap.put(s.charAt(i), hMap.getOrDefault(s.charAt(i), 0) + 1);
            hMap.put(t.charAt(i), hMap.getOrDefault(t.charAt(i), 0) - 1);
        }
        for (int v: hMap.values()) {
            if (v != 0) {
                return false;
            }
        }
        return true;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

StringHashMap

Date

2026-02-03
View Problem Source