Starter

Valid Anagram

Problem
LC 242
Difficulty
Easy
Pattern
Counting
File
leetcode3ValidAnagram.java
Path
pkg5leetcode/leetcode3ValidAnagram.java
Package
pkg5leetcode
Command
java pkg5leetcode/leetcode3ValidAnagram.java

Return true if t is an anagram of s.

Approach
count characters; all counts must cancel to zero.
Complexity
Time O(n), Space O(1) for fixed lowercase alphabet.

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/leetcode3ValidAnagram.java
1package pkg5leetcode;2 3/*4 * LeetCode 242: Valid Anagram  (Easy)5 * -----------------------------------6 * Return true if t is an anagram of s.7 *8 * APPROACH: count characters; all counts must cancel to zero.9 * COMPLEXITY: Time O(n), Space O(1) for fixed lowercase alphabet.10 */11public class leetcode3ValidAnagram {12 13    static boolean isAnagram(String s, String t) {14        if (s.length() != t.length()) return false;15        int[] count = new int[26];16        for (int i = 0; i < s.length(); i++) {17            count[s.charAt(i) - 'a']++;18            count[t.charAt(i) - 'a']--;19        }20        for (int c : count) if (c != 0) return false;21        return true;22    }23 24    public static void main(String[] args) {25        check(isAnagram("anagram", "nagaram"), "anagram");26        check(!isAnagram("rat", "car"), "rat/car");27        check(!isAnagram("a", "ab"), "different length");28        check(isAnagram("", ""), "empty");29        System.out.println("leetcode3ValidAnagram: all tests passed");30    }31 32    static void check(boolean cond, String name) {33        if (!cond) throw new AssertionError("FAILED: " + name);34        System.out.println("  PASS " + name);35    }36}