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?- A. True False
- B. False True
- C. True True
- 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
- Problem: A DP table for a 2 × 3 grid is created in two ways and one cell is set in each. python dp = [[0] 3] 2 dp[0][1] = 5 dp2 = [[0] 3…
- Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts. python def oddsumsubarrays(a): even, odd, run, res…
- Problem: Find the length of the LONGEST contiguous subarray whose sum equals k; values can be negative, so a sliding window is not valid…
- Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window. python def…
- Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and…
- Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each…