Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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] <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Sliding Window
[1,3,2,2,5,2,3,7]
[1,2,3,4]
[1,1,1,1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #594: Longest Harmonious Subsequence
class Solution {
public int findLHS(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
int ans = 0;
for (var e : cnt.entrySet()) {
int x = e.getKey(), c = e.getValue();
if (cnt.containsKey(x + 1)) {
ans = Math.max(ans, c + cnt.get(x + 1));
}
}
return ans;
}
}
// Accepted solution for LeetCode #594: Longest Harmonious Subsequence
func findLHS(nums []int) (ans int) {
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
for x, c := range cnt {
if c1, ok := cnt[x+1]; ok {
ans = max(ans, c+c1)
}
}
return
}
# Accepted solution for LeetCode #594: Longest Harmonious Subsequence
class Solution:
def findLHS(self, nums: List[int]) -> int:
cnt = Counter(nums)
return max((c + cnt[x + 1] for x, c in cnt.items() if cnt[x + 1]), default=0)
// Accepted solution for LeetCode #594: Longest Harmonious Subsequence
use std::collections::HashMap;
impl Solution {
pub fn find_lhs(nums: Vec<i32>) -> i32 {
let mut cnt = HashMap::new();
for &x in &nums {
*cnt.entry(x).or_insert(0) += 1;
}
let mut ans = 0;
for (&x, &c) in &cnt {
if let Some(&y) = cnt.get(&(x + 1)) {
ans = ans.max(c + y);
}
}
ans
}
}
// Accepted solution for LeetCode #594: Longest Harmonious Subsequence
function findLHS(nums: number[]): number {
const cnt: Record<number, number> = {};
for (const x of nums) {
cnt[x] = (cnt[x] || 0) + 1;
}
let ans = 0;
for (const [x, c] of Object.entries(cnt)) {
const y = +x + 1;
if (cnt[y]) {
ans = Math.max(ans, c + cnt[y]);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.