πΉ Problem: 594. Longest Harmonious Subsequence
Difficulty: #Easy
Tags: #Array, #Sliding Window, #Sorting
π Problem Summary
Given an array of integers
nums
, return the length of the longest harmonious subsequence, where the difference between the maximum and minimum element is exactly 1.A subsequence is a sequence that can be derived from the array without changing the order of elements, and it doesn't have to be contiguous.
π§ My Thought Process
Brute Force Idea:
Loop through each element, and for each one, count how many elements exist with a value either equal to it or just one greater. This works but takes O(nΒ²) β not optimal.-
Optimized Strategy:
I figured out that sorting simplifies the problem. After sorting:- Use a sliding window (
j
andi
) to keep track of the current window of elements. - If the difference between
nums[i]
andnums[j]
is greater than 1, movej
forward until the condition is satisfied. - If the difference is exactly 1, check the length of the current subarray and update the maximum length.
- Use a sliding window (
At first, I used an if
condition to adjust j
, but it failed for cases where multiple elements needed to be skipped. The fix? Replace the if
with a while
loop β and boom, it worked.
βοΈ Code Implementation (Python)
class Solution:
def findLHS(self, nums):
nums.sort()
j = 0
maxLength = 0
for i in range(len(nums)):
while nums[i] - nums[j] > 1:
j += 1
if nums[i] - nums[j] == 1:
maxLength = max(maxLength, i - j + 1)
return maxLength
β±οΈ Time & Space Complexity
- Time: O(n log n) β Sorting dominates
- Space: O(1) β No extra space besides a few variables
π§© Key Takeaways
- β Sliding window works best when dealing with ranges or intervals after sorting.
- π‘ The tricky part was updating the left pointer properly β an
if
wasnβt enough.while
is your best friend in sliding window problems. - π Iβll recognize similar problems whenever a sorted array is involved and I need to track windowed properties like differences or frequencies.
π Reflection (Self-Check)
- [x] Could I solve this without help? β Yes!
- [x] Did I write code from scratch? β Yup, just needed to tweak a loop.
- [x] Did I understand why it works? β 100%.
- [x] Will I be able to recall this in a week? β Absolutely.
π Progress Tracker
Metric | Value |
---|---|
Day | 35 |
Total Problems Solved | 368 |
Confidence Today | π |
Top comments (0)