Chaturmind
LearnDSASystem DesignDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Strings›Valid Anagram
EasyStrings

Valid Anagram

stringhash-mapsorting

Problem

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

Examples

Example 1

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

Output: true

Example 2

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

Output: false

Constraints

  • •1 <= s.length, t.length <= 5*10^4
  • •s and t consist of lowercase English letters.

Hints

Hint 1

The brute force: sort both strings and compare them directly — anagrams become identical strings once sorted.

Hint 2

Sorting costs O(n log n) — can you determine anagram-ness without ever reordering anything?

Hint 3

Since both strings must contain the exact same characters the exact same number of times, a single frequency count (increment for one string, decrement for the other) answers the question in one pass.

Solutions

public boolean isAnagramSorting(String s, String t) {
    if (s.length() != t.length()) return false;
    char[] sChars = s.toCharArray();
    char[] tChars = t.toCharArray();
    Arrays.sort(sChars);
    Arrays.sort(tChars);
    return Arrays.equals(sChars, tChars);
}

Time: O(n log n) · Space: O(n) for the sorted copies