Longest Harmonious Subsequence (LeetCode 594): Solution and Explanation
Given an integer array, find the longest subsequence whose largest and smallest values differ by exactly one.
Intuition
A harmonious subsequence contains exactly two distinct values, v and v + 1. Once you pick those two values, the best move is to take every copy of both.
A subsequence can skip elements freely, so the original order never gets in the way. That means we are free to sort.
After sorting, every copy of v sits right before every copy of v + 1. The best pick for that pair is one contiguous window, so a sliding window over the sorted array finds the answer.
Grow the window with right. When nums[right] is more than nums[left] + 1, the left value can never pair with anything to the right, so move left. Whenever the window spans exactly 1, its length is a candidate.
Approach: Sort, then sliding window
- Sort
numsin ascending order. - Set
best = 0andleft = 0. - For each
right, moveleftforward whilenums[right] > nums[left] + 1. - If
nums[right] == nums[left] + 1, the window holds two neighbouring values; updatebestwithright - left + 1. - Return
best. It stays 0 when no two values differ by exactly 1.
Step-by-step example
nums = [1,3,2,2,5,2,3,7]
- Sorting gives [1,2,2,2,3,3,5,7].
- right = 1 to 3 add the 2s. The window [1,2,2,2] spans 1, so best grows to 4.
- right = 4 brings in 3, which is more than 1 + 1, so left moves past the 1. The window [2,2,2,3] spans 1 and has length 4.
- right = 5 adds another 3. The window [2,2,2,3,3] has length 5, the new best.
- right = 6 brings in 5, so left runs past every 2 and 3. The window [5] and later [7] never span exactly 1, so the answer stays 5.
Code: Python, Java, C++
1class Solution:
2 def findLHS(self, nums: List[int]) -> int:
3 nums.sort()
4 best = left = 0
5 for right in range(len(nums)):
6 while nums[right] > nums[left] + 1:
7 left += 1
8 if nums[right] == nums[left] + 1:
9 best = max(best, right - left + 1)
10 return best1class Solution {
2 public int findLHS(int[] nums) {
3 Arrays.sort(nums);
4 int best = 0, left = 0;
5 for (int right = 0; right < nums.length; right++) {
6 while (nums[right] > nums[left] + 1) {
7 left++;
8 }
9 if (nums[right] == nums[left] + 1) {
10 best = Math.max(best, right - left + 1);
11 }
12 }
13 return best;
14 }
15}1class Solution {
2public:
3 int findLHS(vector<int>& nums) {
4 sort(nums.begin(), nums.end());
5 int best = 0, left = 0;
6 for (int right = 0; right < (int)nums.size(); right++) {
7 while (nums[right] > nums[left] + 1) {
8 left++;
9 }
10 if (nums[right] == nums[left] + 1) {
11 best = max(best, right - left + 1);
12 }
13 }
14 return best;
15 }
16};Time and space complexity
O(n log n)
Sorting dominates. The window scan is linear because left and right each move forward at most n times.
O(1)
Apart from the sort itself, only two pointers and the best length are stored.
Other approaches
Hash map of counts (time O(n), space O(n))
Count every value, then for each key v with v + 1 also present, take count[v] + count[v + 1]. This avoids sorting.
Try every value pair by brute force (time O(n^2), space O(1))
For each element pick it as the minimum and count how many elements equal it or it plus one, checking that at least one equals it plus one.
Common mistakes
- Counting a group of equal values as harmonious. The difference must be exactly 1, so [1,1,1,1] gives 0.
- Writing
nums[right] - nums[left] > 1in Java, C++ or C#. With values near plus and minus 10^9 the subtraction overflows; compare againstnums[left] + 1instead. - Treating the problem as a subarray problem. Subsequences can skip elements, which is why sorting is allowed.
- Only checking
v + 1whenvappears first in the input. The order of values does not matter after counting or sorting.
Frequently asked questions
Why is it fine to sort when the problem asks for a subsequence?
The answer only depends on how many copies of v and v + 1 exist. Any set of indices can be listed in its original order, so sorting does not change which subsequences are possible.
Which approach should I use in an interview?
The hash map is O(n) and short. The sorted window shows the same idea with O(1) extra space; both are accepted, and mentioning the trade-off helps.
What if no two values differ by exactly one?
Return 0. The window never satisfies the check, so best keeps its starting value.