Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: A login service flags an account if the same device ID appears twice within at most k positions of the access log (|i − j| ≤ k).

Problem: A login service flags an account if the same device ID appears twice within at most k positions of the access log (|i − j| ≤ k).
def near_dup(a, k):
    last = {}
    for i, x in enumerate(a):
        if x in last and i - last[x] <= k:
            return True
        last[x] = i
    return False
print(near_dup([4, 1, 2, 4, 1], 2), near_dup([4, 1, 2, 4, 1], 3))
What is printed?
  1. A. True False
  2. B. False True
  3. C. True True
  4. D. False False

Correct answer: B. False True

Store only the LAST index of every value: the nearest earlier copy is the only one that can satisfy the distance test. Both repeats here (4 at 0 and 3, 1 at 1 and 4) are exactly 3 apart, so k = 2 fails and k = 3 succeeds. O(n) time; a sliding set of the last k values would also work with O(k) space.

More Coding Interview Problems questions

Exams that ask this topic