Circling the Garage

Easyhash mapAlso known as Contains Duplicate II

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

The manager wants to know if that happened: the same plate coming in twice within a few entries of itself. The same car returning hours later is a normal visit, not 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 came in at positions 1 and 3. 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 came in twice, at positions 0 and 4. 4 - 0 = 4 is more than k = 3, so that was a normal second visit. No other plate repeats. The answer is false.

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

Plate 8 came in at 0, 4 and 6. Comparing with its first visit gives gaps of 4 and 6, both too big. But visits 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

For each entry, compare it with the next k entries and return true on a match.

That costs about n × k comparisons. With 100,000 entries and k = 100,000 it is billions of checks. The waste is that every entry looks forward again over cars the 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