Skip to content

Commit c5e3050

Browse files
Solution Leetcode and Explaination Every single line
1 parent 1492085 commit c5e3050

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
✅ LeetCode 594 – Longest Harmonious Subsequence
2+
3+
public class Solution {
4+
public int findLHS(int[] nums) {
5+
Map<Integer, Integer> map = new HashMap<>();
6+
int maxLen = 0;
7+
8+
for (int num : nums) {
9+
map.put(num, map.getOrDefault(num, 0) + 1);
10+
}
11+
12+
for (int key : map.keySet()) {
13+
if (map.containsKey(key + 1)) {
14+
maxLen = Math.max(maxLen, map.get(key) + map.get(key + 1));
15+
}
16+
}
17+
18+
return maxLen;
19+
}
20+
}
21+
22+
Explanation
23+
24+
Map<Integer, Integer> map = new HashMap<>();
25+
🔹 Har number ka count store karne ke liye frequency map bana rahe hain.
26+
27+
for (int num : nums)
28+
 map.put(num, map.getOrDefault(num, 0) + 1);
29+
30+
🔹 Har element ka occurrence count update karte ja rahe hain.
31+
32+
for (int key : map.keySet())
33+
🔹 Har unique element par loop kar rahe hain.
34+
35+
if (map.containsKey(key + 1))
36+
 maxLen = Math.max(maxLen, map.get(key) + map.get(key + 1));
37+
38+
🔹 Check kar rahe hain kya key ke next element (key + 1) bhi present hai.
39+
Agar haan, toh key aur key+1 dono milke ek harmonious subsequence banayenge.
40+
Unka combined count (frequency) hi subsequence length hoga.
41+
42+
return maxLen;
43+
🔹 Sabse longest valid subsequence ka length return kar diya.
44+
45+
🧪 Example Dry Run
46+
Input:
47+
nums = [1,3,2,2,5,2,3,7]
48+
Frequency Map:
49+
1→1, 2→3, 3→2, 5→1, 7→1
50+
51+
Valid Pairs:
52+
53+
1 & 2 → 1 + 3 = 4
54+
55+
2 & 3 → 3 + 2 = 5 ✅
56+
57+
3 & 4 ❌
58+
59+
5 & 6 ❌
60+
61+
7 & 8 ❌
62+
63+
Output: 5
64+
65+
Time & Space Complexity
66+
Item Complexity
67+
Time O(N)
68+
Space O(N)
69+
70+
🔗 Need more help or Java tricks?
71+
https://www.linkedin.com/in/saurabh884095/
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import java.util.;
2+
3+
public class Solution {
4+
public int findLHS(int[] nums) {
5+
MapInteger, Integer map = new HashMap();
6+
int maxLen = 0;
7+
8+
for (int num nums) {
9+
map.put(num, map.getOrDefault(num, 0) + 1);
10+
}
11+
12+
for (int key map.keySet()) {
13+
if (map.containsKey(key + 1)) {
14+
maxLen = Math.max(maxLen, map.get(key) + map.get(key + 1));
15+
}
16+
}
17+
18+
return maxLen;
19+
}
20+
}

0 commit comments

Comments
 (0)