Circling the Garage

Easyhash mapAlso known as Contains Duplicate II

A camera at a parking garage entrance logs the plate of every car that drives in, in order. A driver who finds no free spot leaves by the exit ramp and often comes straight back in.

The manager wants to detect this, which means finding the same plate entering twice within a few log entries. The same car returning hours later is a normal visit and does not count as circling.

Your task

Write circlingCar(plates, k). Return true if there are two positions i < j with plates[i] === plates[j] and j - i ≤ k. Otherwise return false.

An empty log returns false. With k = 0 no pair can qualify, so the answer is false.

circlingCar(plates: int[], k: int) → bool

Examples

Example 1
Input
plates = [512, 77, 903, 77, 640]
k = 2
Output
true
Why

Plate 77 entered at positions 1 and 3. The gap is 3 - 1 = 2, which is within k = 2, so the answer is true.

Example 2
Input
plates = [512, 77, 903, 640, 512]
k = 3
Output
false
Why

Plate 512 entered at 0 and 4. 4 - 0 = 4 is more than k = 3, so that was a normal second visit. No other plate repeats, so the answer is false.

Example 3
Input
plates = [8, 1, 2, 3, 8, 4, 8]
k = 2
Output
true
Why

Plate 8 entered at positions 0, 4 and 6. The gaps from the first visit, 4 and 6, are too big, but the visits at positions 4 and 6 are only 2 apart, so the answer is true.

Constraints

  • 0 ≤ plates.length ≤ 100,000
  • 0 ≤ plates[i] ≤ 1,000,000,000
  • 0 ≤ k ≤ 100,000
Start with brute force

Compare each entry with the next k entries and return true on a match.

That is about n × k comparisons: billions with 100,000 entries and k = 100,000. Each entry rescans cars that earlier entries already looked at.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code