logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

242. Valid Anagram

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

Two strings are anagrams if they contain the same characters with the exact same frequency, just possibly in a different order.

So, we don’t care where characters are — just how many times each character appears in both strings.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(N)\text{O}(N)O(N)

# Code

public boolean isAnagram(String firstString, String secondString) {
    // Arrays to store character frequencies
    int[] freqFirst = new int[26];
    int[] freqSecond = new int[26];
 
    int lengthFirst = firstString.length();
    int lengthSecond = secondString.length();
 
    // If lengths are different, they can't be anagrams
    if (lengthFirst != lengthSecond) return false;
 
    // Count characters in both strings
    for (int i = 0; i < lengthFirst; ++i) {
        freqFirst[firstString.charAt(i) - 'a']++;
        freqSecond[secondString.charAt(i) - 'a']++;
    }
 
    // Compare frequency of each character
    for (int i = 0; i < 26; ++i) {
        if (freqFirst[i] != freqSecond[i]) return false;
    }
 
    return true; // All counts matched =&gt; anagram
}
 
←Previous205. Isomorphic StringsNext→283. Move Zeroes

On this page

IntuitionComplexityCode