KatInterview

594. Longest Harmonious Subsequence

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

A harmonious subsequence is defined as a subsequence where the difference between its maximum and minimum value is exactly 1. This means a harmonious subsequence can only be composed of two distinct numbers, x and x + 1. The problem asks for the length of the longest such subsequence.

Solution

Longest Harmonious Subsequence in Python

class Solution:
    def findLHS(self, nums: List[int]) -> int:
        # Use a hash map (collections.Counter) to store the frequency of each number.
        counts = collections.Counter(nums)
        maxLength = 0
        
        # Iterate through each number 'num' in the frequency map.
        for num in counts:
            # Check if a harmonious pair (num, num + 1) exists.
            if num + 1 in counts:
                # Calculate the length of this harmonious subsequence.
                currentLength = counts[num] + counts[num + 1]
                # Update the maximum length found so far.
                maxLength = max(maxLength, currentLength)
                
        return maxLength

Longest Harmonious Subsequence in Java

class Solution {
    public int findLHS(int[] nums) {
        // Create a HashMap to store the frequency of each number.
        java.util.Map<Integer, Integer> counts = new java.util.HashMap<>();
        for (int num : nums) {
            counts.put(num, counts.getOrDefault(num, 0) + 1);
        }
        
        int maxLength = 0;
        
        // Iterate through the keys of the map.
        for (int num : counts.keySet()) {
            // Check if the number 'num + 1' exists in the map.
            if (counts.containsKey(num + 1)) {
                // Calculate the length of the harmonious subsequence.
                int currentLength = counts.get(num) + counts.get(num + 1);
                // Update the maximum length.
                maxLength = Math.max(maxLength, currentLength);
            }
        }
        
        return maxLength;
    }
}

Longest Harmonious Subsequence in C++

class Solution {
public:
    int findLHS(vector<int>& nums) {
        // Use an unordered_map to store the frequency of each number.
        std::unordered_map<int, int> counts;
        for (int num : nums) {
            counts[num]++;
        }
        
        int maxLength = 0;
        
        // Iterate through the key-value pairs in the map.
        for (auto const& [num, count] : counts) {
            // Check if 'num + 1' exists in the map.
            // Using .count() is a safe way to check for key existence.
            if (counts.count(num + 1)) {
                // Calculate the length of the harmonious subsequence.
                // We can use .at() for safe access after the check.
                int currentLength = count + counts.at(num + 1);
                // Update the maximum length.
                maxLength = std::max(maxLength, currentLength);
            }
        }
        
        return maxLength;
    }
};

Longest Harmonious Subsequence in TypeScript

function findLHS(nums: number[]): number {
    // Use a Map to store the frequency of each number.
    const counts = new Map<number, number>();
    for (const num of nums) {
        counts.set(num, (counts.get(num) || 0) + 1);
    }

    let maxLength = 0;

    // Iterate through the entries [number, count] of the map.
    for (const [num, count] of counts.entries()) {
        // Check if 'num + 1' exists in the map.
        if (counts.has(num + 1)) {
            // Calculate the length of the harmonious subsequence.
            // Use the non-null assertion operator (!) since we know the key exists.
            const currentLength = count + counts.get(num + 1)!;
            // Update the maximum length.
            maxLength = Math.max(maxLength, currentLength);
        }
    }

    return maxLength;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.