Practice › Hashing & Two Pointers
Longest Harmonious Subsequence
Easy · Hashing & Two Pointers · Asked at LinkedIn, Amazon, Google
A sequence is harmonious if its maximum and minimum differ by exactly 1. Print the length of the longest harmonious subsequence of the array, or 0 if there is none.
Input
First line: n. Second line: n space-separated integers.
Output
The length of the longest harmonious subsequence.
Constraints
- 1 ≤ n ≤ 10^5
- −10^9 ≤ a[i] ≤ 10^9
A harmonious subsequence uses only two values x and x + 1, and should take every copy of both. Count each value in a hash map and check count[x] + count[x + 1] when both exist.
Example 1
Input
8 1 3 2 2 5 2 3 7
Output
5
Example 2
Input
4 1 1 1 1
Output
0
Hints
- A subsequence can skip elements, so order does not matter.
- A harmonious one uses exactly two values, x and x + 1 — and should use all their copies.
Approach
Count every value in a hash map. For each value x that also has x + 1 present, a candidate length is count[x] + count[x + 1]. Print the largest candidate, or 0 when no two values differ by exactly 1.
Complexity: O(n) expected time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
unordered_map<long long, int> cnt;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
cnt[x]++;
}
int best = 0;
for (auto &p : cnt) {
auto it = cnt.find(p.first + 1);
if (it != cnt.end()) best = max(best, p.second + it->second);
}
cout << best << "\n";
return 0;
}Python solution
import sys
from collections import Counter
data = list(map(int, sys.stdin.read().split()))
cnt = Counter(data[1 : 1 + data[0]])
print(max((c + cnt[x + 1] for x, c in cnt.items() if x + 1 in cnt), default=0))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
HashMap<Long, Integer> cnt = new HashMap<>();
for (int i = 0; i < n; i++) {
in.nextToken();
cnt.merge((long) in.nval, 1, Integer::sum);
}
int best = 0;
for (Map.Entry<Long, Integer> e : cnt.entrySet()) {
Integer other = cnt.get(e.getKey() + 1);
if (other != null) best = Math.max(best, e.getValue() + other);
}
System.out.println(best);
}
}Solve Longest Harmonious Subsequence online · All practice problems