Longest Harmonious Subsequence (LeetCode 594): Solution and Explanation

Easy
Array
Hash Table
Sliding Window
Sorting
Counting

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

  1. Sort nums in ascending order.
  2. Set best = 0 and left = 0.
  3. For each right, move left forward while nums[right] > nums[left] + 1.
  4. If nums[right] == nums[left] + 1, the window holds two neighbouring values; update best with right - left + 1.
  5. 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]
  1. Sorting gives [1,2,2,2,3,3,5,7].
  2. right = 1 to 3 add the 2s. The window [1,2,2,2] spans 1, so best grows to 4.
  3. 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.
  4. right = 5 adds another 3. The window [2,2,2,3,3] has length 5, the new best.
  5. 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 best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates. The window scan is linear because left and right each move forward at most n times.

Space

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] > 1 in Java, C++ or C#. With values near plus and minus 10^9 the subtraction overflows; compare against nums[left] + 1 instead.
  • Treating the problem as a subarray problem. Subsequences can skip elements, which is why sorting is allowed.
  • Only checking v + 1 when v appears 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.