Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Sorting
Longest Harmonious Subsequence

Find the length of the longest subsequence where the maximum and minimum values differ by exactly 1.

Acceptance 100%
Problem Statement

Given an integer array, find the length of the longest harmonious subsequence.

A subsequence is harmonious if the difference between its largest and smallest values is exactly 1. The elements of the subsequence do not need to be contiguous, but they must come from the original array.

Your task is to return the maximum possible length of such a subsequence. If no harmonious subsequence exists, return 0.

Input Format

  • An integer array nums.
  • nums[i] is an integer element of the array.

Output Format

  • Return a single integer: the length of the longest harmonious subsequence.

Constraints

  • The subsequence may skip elements, but order is inherited from the original array.
  • A valid harmonious subsequence must contain at least two distinct values.
  • The value range and array length are not fixed here; solve efficiently using counting or sorting.
Examples
Sample cases returned by the problem API.

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], which contains only 2 and 3, and the difference between max and min is 1.

Example 2

Input

nums = [1,1,1,1]

Output

0

Explanation

All elements are the same, so there is no subsequence whose max and min differ by exactly 1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.