#594

Longest Harmonious Subsequence

Easy
ArrayHash TableSliding WindowSortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a frequency map to count occurrences of each number. By checking adjacent numbers in this map, we can efficiently find the longest harmonious subsequence without generating all subsequences.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency map to count occurrences of each number in the array.
  2. 2Step 2: Iterate through the keys in the frequency map.
  3. 3Step 3: For each key, check if the key + 1 exists in the map. If it does, calculate the length of the harmonious subsequence.
  4. 4Step 4: Keep track of the maximum length found.
solution.py10 lines
1# Full working Python code
2from collections import Counter
3
4def findLHS(nums):
5    freq = Counter(nums)
6    max_length = 0
7    for key in freq:
8        if key + 1 in freq:
9            max_length = max(max_length, freq[key] + freq[key + 1])
10    return max_length

Complexity note: The time complexity is O(n) because we traverse the array once to build the frequency map and then iterate through the map, which is efficient. The space complexity is O(n) due to the storage of the frequency map.

  • 1Utilizing a frequency map can significantly reduce the complexity of the problem.
  • 2Harmonious subsequences can only be formed by adjacent numbers in the frequency map.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.