Skip to main content

Longest Harmonious Subsequence - Solution & Explanation

EasyArrayHash TableSliding WindowSorting15 min readAsked at: Amazon, Microsoft, Meta +4
Practice this problem

Problem Statement

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.

 

Example 1:

Input: nums = [1,3,2,2,5,2,3,7]

Output: 5

Explanation:

The longest harmonious subsequence is [3,2,2,2,3].

Example 2:

Input: nums = [1,2,3,4]

Output: 2

Explanation:

The longest harmonious subsequences are [1,2], [2,3], and [3,4], all of which have a length of 2.

Example 3:

Input: nums = [1,1,1,1]

Output: 0

Explanation:

No harmonic subsequence exists.

 

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -109 <= nums[i] <= 109

Approach Overview

Problem Overview: Given an integer array nums, find the length of the longest harmonious subsequence. A subsequence is harmonious if the difference between its maximum and minimum values is exactly 1. Elements do not need to remain contiguous, but they must come from the original array.

Approach 1: HashMap for Counting Elements (O(n) time, O(n) space)

This approach counts the frequency of every number using a hash map. After building the frequency table, iterate through each unique value x and check whether x + 1 exists. If it does, the total length of a harmonious subsequence formed by those values is count[x] + count[x+1]. Track the maximum across all such pairs. The key insight: a harmonious subsequence only depends on the counts of two consecutive integers, not their positions. Hash lookups run in constant time, so the entire process completes in O(n) time. This method heavily relies on efficient counting with a hash table and works well for unsorted arrays.

Approach 2: Sorting + Sliding Window (O(n log n) time, O(1) extra space)

Another option sorts the array first. Once sorted, numbers with similar values appear next to each other. Use two pointers to maintain a window where the difference between the current maximum and minimum stays ≤ 1. Expand the right pointer while the condition holds. If the difference exceeds 1, move the left pointer forward. Whenever the difference equals exactly 1, update the maximum window length. Sorting costs O(n log n), while the two-pointer scan runs in O(n). This approach is intuitive if you are comfortable with sorting and sliding window patterns.

The sorted method works well when modifying the input array is acceptable and you prefer pointer-based reasoning. The hash map approach is typically faster in practice because it avoids sorting and directly uses element frequencies.

Recommended for interviews: The hash map counting approach is usually what interviewers expect. It demonstrates strong understanding of frequency counting and constant-time lookups. Mentioning the sorting approach shows you considered multiple strategies, but implementing the O(n) hash-based solution proves you can optimize beyond brute-force comparisons.

Approach 1: HashMap for Counting Elements

This approach leverages a map (or dictionary in Python) to count the frequency of each number in the array. Once we know the count of each number, we can iterate through the keys and check for pairs of consecutive numbers (n and n+1). The length of a harmonious subsequence that can be formed is the sum of the counts of these consecutive numbers.

The C solution uses an array to act as a hashmap to count occurrences of numbers. A large integer array of size 2 billion is declared to accommodate the range of input, offset by 1 billion to handle negative values by shifting index.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), Space Complexity: O(n)

Try this approach in the editor →

Approach 2: Sorting Solution

An alternative approach would be to sort the numbers. After sorting, we can use a two-pointer technique to find the longest subsequence where the difference between the smallest and largest value is exactly one. This method may be less efficient due to the sorting step but provides a straightforward solution.

The C implementation uses the qsort function to first sort the array, and then applies a two-pointer technique to find the longest subsequence with the desired difference of one.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) due to sorting, Space Complexity: O(1) if counting sort or constant space partition approach is used.

Try this approach in the editor →

Approach 3: Hash Table

We can use a hash table cnt to record the occurrence count of each element in the array nums. Then, we iterate through each key-value pair (x, c) in the hash table. If the key x + 1 exists in the hash table, then the sum of occurrences of elements x and x + 1, c + cnt[x + 1], forms a harmonious subsequence. We just need to find the maximum length among all harmonious subsequences.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
HashMap for Counting Elements

Time Complexity: O(n), Space Complexity: O(n)

Sorting Solution

Time Complexity: O(n log n) due to sorting, Space Complexity: O(1) if counting sort or constant space partition approach is used.

Hash Table—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
HashMap for Counting ElementsO(n)O(n)Best general solution. Works efficiently for unsorted arrays using frequency counting.
Sorting + Sliding WindowO(n log n)O(1) extraUseful when sorting is acceptable and you prefer two-pointer window logic.

Video Solution

Longest Harmonious Subsequence | Live Coding with Explanation | Leetcode #594 • Algorithms Made Easy • 10,264 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Harmonious Subsequence easy or hard?
Longest Harmonious Subsequence is classified as an Easy problem on LeetCode with an acceptance rate around 64%. The challenge mainly involves recognizing that only counts of consecutive numbers matter, making a hash map frequency approach ideal.
How to solve Longest Harmonious Subsequence in O(n)?
Count the occurrences of each number using a hash map. Then iterate through the keys and check if the map contains key+1. If it does, combine their frequencies to form a harmonious subsequence and update the maximum length.
What is the best approach for Longest Harmonious Subsequence?
The most efficient approach uses a hash map to count the frequency of each number. For every value x, check whether x+1 exists and compute count[x] + count[x+1]. This finds the longest harmonious subsequence in O(n) time with O(n) space.
What data structure is used in Longest Harmonious Subsequence?
A hash table (hash map) is the primary data structure used in the optimal solution. It stores the frequency of each number and enables constant-time lookups when checking for adjacent values like x and x+1.
What is the time complexity of Longest Harmonious Subsequence?
The optimal hash map solution runs in O(n) time because it scans the array once to build frequencies and once more to check adjacent values. The sorting-based solution takes O(n log n) due to the initial sort.
Longest Harmonious Subsequence Python or Java solution approach?
Both Python and Java implementations follow the same idea: build a frequency map using a dictionary or HashMap, then iterate through the keys to check pairs of consecutive numbers. The algorithm runs in O(n) time and O(n) space.
Is Longest Harmonious Subsequence asked at Google, Amazon, or Meta?
This problem represents a common interview pattern involving frequency counting and hash maps. Variants of similar array counting questions appear in interviews at companies like Amazon and Google because they test understanding of hash tables and linear-time optimization.

Ready to solve this problem?

Practice Longest Harmonious Subsequence with our built-in code editor and test cases.

Practice on FleetCode