Longest Harmonious Subsequence
EasyArrays & Hashinghashing
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Call an array **harmonious** when its maximum and minimum values differ by exactly 1.
Given an integer array nums, return the length of the longest harmonious **subsequence** (elements taken in their original order, not necessarily contiguous). If no harmonious subsequence exists, return 0.
Examples
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
The subsequence [3,2,2,2,3] has max 3 and min 2.
Input: nums = [1,2,3,4]
Output: 2
Any adjacent pair of values such as [1,2] works.
Input: nums = [1,1,1,1]
Output: 0
Every element is equal, so max - min is 0, never 1.
Constraints
- 1 <= nums.length <= 2 * 10^4
- -10^9 <= nums[i] <= 10^9
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.