↓Skip to main content
  1. LeetCode/

LeetCode 594: Longest Harmonious Subsequence

·1 min· ·
LeetCode Easy Array Hash-Table Sliding-Window Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-28

  • Submissions: Accepted ×2 → Runtime Error

Approach
#

Subsequences are not contiguous, so order does not matter: just count (Hash Table Template 1). A harmonious subsequence holds only x and x + 1; for each x with x + 1 present, a candidate is cnt[x] + cnt[x + 1]. Checking x + 1 suffices because the x - 1 pairing is handled at x - 1.

My Solution
#

class Solution:
    def findLHS(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        return max((cnt[x] + cnt[x + 1] for x in cnt if x + 1 in cnt), default=0)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • A single distinct value is not harmonious; return 0.

Interview Explanation
#

Since a subsequence need not be contiguous I just count, and for each value x with x + 1 present I update the answer with their combined count. Time O(n).

Related

LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 219: Contains Duplicate II
·2 mins
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 note: a hash map stores each value’s last index; only the most recent occurrence needs a distance check
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 506: Relative Ranks
·1 min
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 note: sort indices by score descending, give medals to the top three and rank strings to the rest, writing back into the original positions
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them