Longest Harmonious Subsequence - Problem

We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.

Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.

Note: A subsequence is derived from an array by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Harmonious Array
$ Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
💡 Note: The longest harmonious subsequence is [3,2,2,2,3] with length 5. It contains numbers 2 and 3, and 3-2=1.
Example 2 — No Harmonious Subsequence
$ Input: nums = [1,2,3,4]
Output: 2
💡 Note: Multiple harmonious subsequences exist: [1,2], [2,3], [3,4], each with length 2. Return the maximum length which is 2.
Example 3 — All Same Numbers
$ Input: nums = [1,1,1,1]
Output: 0
💡 Note: All numbers are the same, so max-min=0, not 1. No harmonious subsequence exists.

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Longest Harmonious Subsequence INPUT nums array: 1 3 2 2 5 2 3 7 indices: 0-7 Harmonious Array: max - min = 1 Example: [2,2,2,3,3] 3 - 2 = 1 (OK) Input Values nums = [1,3,2,2,5,2,3,7] Length: 8 Find longest harmonious subseq ALGORITHM STEPS 1 Build Frequency Map Count occurrences of each num Key: 1 | Count: 1 Key: 2 | Count: 3 Key: 3 | Count: 2 Key: 5 | Count: 1 Key: 7 | Count: 1 2 For Each Key Check if key+1 exists in map 3 Calculate Length count[key] + count[key+1] key=1: 1+0=1 (no key 2? wait..) key=2: 3+2=5 (2s + 3s) key=3: 2+0=2 (no key 4) 4 Track Maximum Update max length found FINAL RESULT Longest Harmonious Subsequence: 2 2 2 3 3 [2, 2, 2, 3, 3] max = 3, min = 2 3 - 2 = 1 (OK) Harmonious condition met! OUTPUT 5 Length = 5 3 twos + 2 threes Key Insight: Using a hash map allows O(n) counting of elements. For each unique number k, if k+1 exists, the harmonious subsequence length is count[k] + count[k+1]. Track the maximum across all pairs. Time: O(n) | Space: O(n) for the hash map TutorialsPoint - Longest Harmonious Subsequence | Hash Map Approach
Asked in
Amazon 15 Facebook 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen