Skip to content
Problem 594 · LeetCode 594(opens in a new tab)

Longest Harmonious Subsequence

EasyArrays

Call a list harmonious when its largest value is exactly 1 more than its smallest value.

From the integer array nums, pick the longest harmonious subsequence and report how many elements it has. A subsequence keeps some of the elements in their original order, possibly skipping others. If no harmonious subsequence exists, return 0.

Example 1

Input:  nums = [4, 2, 3, 3, 4, 3, 8]
Output: 5
Why:    keep every 3 and every 4: [4, 3, 3, 4, 3]
2 more examples and the constraints

Example 2

Input:  nums = [10, 11, 12, 11]
Output: 3
Why:    [10, 11, 11] and [11, 12, 11] both have length 3

Example 3

Input:  nums = [7, 7, 7]
Output: 0
Why:    max minus min is 0, never exactly 1

Constraints

  • 1 ≤ length of nums ≤ 20,000
  • −1,000,000,000 ≤ nums[i] ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Scan for each valueO(n²)
  2. Count once, then pairO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 20,000 numbersVerdict
Scan for each valueO(n²)
Correct, recounts too much
Count once, then pairO(n)
Best; one count, one lookup each

n = length of nums.

Edge cases to test

  • All values equal. [7, 7, 7] gives 0: the difference must be exactly 1.
  • A single number. [5] gives 0.
  • Gaps of 2. [1, 3, 5] gives 0: neighbours must differ by exactly 1.
  • Negative values. [-2, -1, -1] gives 3; −1 is the partner of −2.
  • Values at the limits. 999,999,999 and 1,000,000,000 pair up; x + 1 must not overflow in your language.

Common mistakes

  • Counting a single repeated value as harmonious, so [7, 7, 7] returns 3.
  • Looking for a contiguous subarray instead of a subsequence, which misses copies that are far apart.
  • Checking both x − 1 and x + 1 and double counting, or checking neither when only one value exists.

How to talk through it

  1. 1Clarify. Is it a subsequence or a subarray? Must the difference be exactly 1? What if no pair exists?
  2. 2Give the brute force. For each x, scan and count x and x + 1: O(n²).
  3. 3Notice order does not matter. The best subsequence for x takes every x and every x + 1, so only counts matter.
  4. 4Code the counting pass. Build the counts, then check x + 1 for each key.
  5. 5Test out loud. Run [7, 7, 7] and a case with negatives before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?