Skip to content

Commit 7bc5b0a

Browse files
authored
Merge pull request #2046 from pastelto/main
[pastelto] WEEK 02 solutions #218
2 parents 2b45341 + b087c00 commit 7bc5b0a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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

Comments
ย (0)