LeetCode 594: Longest Harmonious Subsequence Solution

Master LeetCode problem 594 (Longest Harmonious Subsequence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

594. Longest Harmonious Subsequence

Problem Explanation

Explanation

To find the length of the longest harmonious subsequence in an array, we can iterate through the array and count the frequency of each number. For each number, we check if its adjacent number (i.e., number + 1 or number - 1) exists in the frequency map. If it does, we calculate the length of the harmonious subsequence by adding the frequencies of both numbers. We keep track of the maximum length found so far and return it as the result.

  • Initialize a map to store the frequency of each number in the array.
  • Iterate through the array and populate the frequency map.
  • For each number, check if its adjacent number exists in the map and calculate the length of the harmonious subsequence.
  • Update the maximum length found so far and return it as the result.

Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(n) for the frequency map.

Solution Code

class Solution {
    public int findLHS(int[] nums) {
        Map<Integer, Integer> freqMap = new HashMap<>();
        int maxLen = 0;

        for (int num : nums) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }

        for (int num : freqMap.keySet()) {
            if (freqMap.containsKey(num + 1)) {
                maxLen = Math.max(maxLen, freqMap.get(num) + freqMap.get(num + 1));
            }
        }

        return maxLen;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 594 (Longest Harmonious Subsequence)?

This page provides optimized solutions for LeetCode problem 594 (Longest Harmonious Subsequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 594 (Longest Harmonious Subsequence)?

The time complexity for LeetCode 594 (Longest Harmonious Subsequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 594 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 594 in Java, C++, or Python.

Back to LeetCode Solutions