Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Viktor Pokazanyev
Python solution with two deques

Viktor Pokazanyev

Feb 1, 2026

from collections import deque class Solution:     def longestSubarray(self, nums, limit):         maxLength = 0         start = 0         min_dq, max_dq = deque(), deque()         for end in range(len(nums)):             # Update max.             while max_dq and max_dq[0] < start:                 max_dq.popleft()             while max_dq and nums[max_dq[-1]] <= nums[end]:                 max_dq.pop()             max_dq.append(end)             # Update min.             while min_dq and min_dq[0] < start:                 min_dq.popleft()             while min_dq and nums[min_dq[-1]] >= nums[end]:                 min_dq.pop()             min_dq.append(end)             # Check limit and update max length.             w_min, w_max = nums[min_dq[0]], nums[max_dq[0]]             if start < end and w_max - w_min > limit:                 start += 1             else:                 maxLength = max(maxLength, end - start + 1)         return maxLength

0

0

Comments