Skip to content
ArrayMedium

Longest Subarray with at most K Distinct

Two-pointer sliding window expands and contracts to maintain at most K unique keys.

Time O(n) Space O(k)
Open in 3D Studio

Live loop — open the studio to scrub, add your own array, or race it in Battle Arena.

Asked in interviews at

AmazonAppleStripe

Reference implementation (Python)

def longest_k_distinct(arr, k=2):
    count = {}; left = max_len = 0
    for right, x in enumerate(arr):
        count[x] = count.get(x, 0) + 1
        while len(count) > k:
            count[arr[left]] -= 1
            if count[arr[left]] == 0: del count[arr[left]]
            left += 1
        max_len = max(max_len, right - left + 1)
    return max_len

Embed this visualization

Drop a live, looping Longest Subarray with at most K Distinct canvas into a blog post or course page.

<iframe src="/embed/longest-subarray-k-distinct" width="100%" height="380" style="border:1px solid #e6e8ec;border-radius:14px" loading="lazy" title="3D algorithm visualization by CodeWithMunnaX"></iframe>

Frequently asked

What is the time and space complexity of Longest Subarray with at most K Distinct?

Longest Subarray with at most K Distinct runs in O(n) time and O(k) auxiliary space.

Is the Longest Subarray with at most K Distinct visualizer free?

The core 3D visualizer, Web Audio chimes and step intuition are free. A one-time ₹49 Pro Pass unlocks advanced algorithms, large custom arrays, Battle Arena and reel export.

Which companies ask Longest Subarray with at most K Distinct in interviews?

Longest Subarray with at most K Distinct shows up in interviews at Amazon, Apple, Stripe.

How does the 3D visualization of Longest Subarray with at most K Distinct work?

Each array value becomes a 3D pillar whose height maps to its value. Comparisons glow amber, swaps flash red, and settled elements lock green while a floating pointer badge tracks the active index — synchronized line-by-line with the Python code.

More Array