1+ class Solution {
2+ /**
3+ * Checks if two strings are anagrams.
4+ *
5+ * Time Complexity: O(n) - where n is the length of the string
6+ * Space Complexity: O(k) - where k is the number of unique characters
7+ *
8+ * @param s First string
9+ * @param t Second string
10+ * @return Return true if it is anagram
11+ */
12+ public boolean isAnagram (String s , String t ) {
13+ // Early return if lengths differ
14+ if (s .length () != t .length ()) return false ;
15+
16+ // Store character frequencies (s: +1, t: -1)
17+ Map <Character , Integer > count = new HashMap <>();
18+
19+ // Calculate frequencies in single pass
20+ for (int i = 0 ; i < s .length (); i ++) {
21+ count .put (s .charAt (i ), count .getOrDefault (s .charAt (i ), 0 ) + 1 );
22+ count .put (t .charAt (i ), count .getOrDefault (t .charAt (i ), 0 ) - 1 );
23+ }
24+
25+ // All frequencies must be 0 for anagram
26+ for (int c : count .values ()) {
27+ if (c != 0 ) return false ;
28+ }
29+
30+ return true ;
31+ }
32+ }
33+
34+ /*
35+ * ============================================================
36+ * SELF REVIEW
37+ * ============================================================
38+ * Problem: Valid Anagram
39+ * Date: 2025-11-18
40+ * Result: Accepted
41+ * Runtime: 25ms (Beats 6.36%)
42+ * Memory: 44.59MB (Beats 52.17%)
43+ *
44+ * APPROACH:
45+ * - HashMap์ ์ด์ฉํ ๋น๋์ ๊ณ์ฐ
46+ *
47+ * COMPLEXITY:
48+ * - Time: O(n), Space: O(k)
49+ *
50+ * KEY LEARNINGS:
51+ * - ํด๋น ๋ฌธ์ ๋ฅผ ๋ณด์๋ง์ HashMap์ ์๊ฐํ๋๋ฐ, ์๊ฐ๋ณด๋ค ์๋ ์ธก๋ฉด์์ ๋ค๋ฅธ ๋ต์์ ๋นํด ๋งค์ฐ ๋๋ ธ๋ค.
52+ * - ๋ค๋ฅธ ๋ฐฉ๋ฒ์ผ๋ก Arrays.sort(), int[] counting ๋ฐฉ์์ด ์์๋ค.
53+ * - ๋ฌธ์ ์ ๋ค์ํ ํด๊ฒฐ ๋ฐฉ์์ ๋ํด์ ๊ณต๋ถ๊ฐ ํ์ํ๋ค.
54+ * ============================================================
55+ */
0 commit comments