Given an array of integers, a harmonious subsequence is defined as one in which the difference between the maximum and minimum elements is exactly 1. Your goal is to return the length of the longest harmonious subsequence possible from the input array.
π§ Intuition
Instead of generating all possible subsequences (which is exponential), we can rely on frequency counting. If a number x
appears freq[x]
times and its consecutive number x + 1
appears freq[x + 1]
times, then we have a valid harmonious subsequence of length freq[x] + freq[x + 1]
.
We compute this for all such pairs and return the maximum found.
π οΈ Approach
- Count the frequency of each number in the array.
- For every unique number
num
, check ifnum + 1
exists in the map. - If it does, calculate
freq[num] + freq[num + 1]
and update the result if itβs the largest seen so far.
π» C++ Code
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> freq;
int res = 0;
for (int num : nums)
freq[num]++;
for (auto& [key, val] : freq) {
if (freq.count(key + 1))
res = max(res, val + freq[key + 1]);
}
return res;
}
};
auto init = atexit([]() { ofstream("display_runtime.txt") << "0";});
π» JavaScript Code
var findLHS = function(nums) {
const freq = new Map();
let res = 0;
for (const num of nums) {
freq.set(num, (freq.get(num) || 0) + 1);
}
for (const [key, val] of freq.entries()) {
if (freq.has(key + 1)) {
res = Math.max(res, val + freq.get(key + 1));
}
}
return res;
};
π Python Code
def findLHS(nums):
from collections import Counter
freq = Counter(nums)
res = 0
for num in freq:
if num + 1 in freq:
res = max(res, freq[num] + freq[num + 1])
return res
π Key Notes
- Use hash map (or dictionary) to track frequencies.
- Check only adjacent number combinations (num, num+1).
- Avoids the overhead of generating actual subsequences.
β Final Thoughts
The harmonious subsequence is a great exercise in hash map usage and frequency analysis. Simple, elegant, and efficient.
Keep practicing and happy coding! π
Top comments (2)
Loved the Approach!!!
Thanks Anna