Longest subarray without duplicates within distance K
Anonymous User
515

You are given an array 𝐴 of of integers, length 𝑁. What is the longest ("sub") array you can generate from 𝐴, such that there are no duplicates within distance 𝐾 of one another. The ("sub") array must be constructed by removing values from 𝐴, i.e., the order must be preserved, but any entry may be skipped/ignored/removed.

Trivial example: For 𝐾=1, 𝐴=[1,2,1,3,2], the answer is: 5 ([1,2,1,3,2]).

Non-trivial example: For 𝐾=2, 𝐴=[1,2,1,3,2], the answer is: 4 ([2,1,3,2]).

Note that in the non-trivial example, we had to skip the first element, such that we could add both 2's; else we would have had [1,2,3].

Desired solution is O(N).

Comments (2)