Ctrl K

Closest Events in a Log

Medium
A user activity log log is a list of words in the order the events happened. Given two words left and right, find the smallest distance between an entry of left and an entry of right, where positions i and j are |i - j| apart. The words left and right may be the same, in which case you need two **different** entries of that word. The required entries are guaranteed to exist (at least two of them when the words are equal).
Example 1
log=["login", "view", "buy", "view", "logout"], left="buy", right="view" → 1

"buy" is at position 2 and "view" at 1 and 3, so the closest pair is 1 apart.

Example 2
log=["view", "buy", "login", "view", "view"], left="view", right="view" → 1

The words coincide, so look for two different "view" entries: positions 3 and 4 are adjacent.

Example 3
log=["pay", "ship", "ship", "ship", "pay"], left="pay", right="pay" → 4

The two "pay" entries are at positions 0 and 4, which are 4 apart.

Constraints
  • 1 ≤ len(log) ≤ 10⁵
  • 1 ≤ len(log[i]) ≤ 10
  • Words consist of lowercase English letters
  • left and right occur in log; if they are equal, the word occurs at least twice
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAnagram Buckets MediumWord Traced on a Letter Grid MediumSplit Into Dictionary Words MediumBiggest Number From Pieces MediumNumbers That Survive a Flip Medium
loading Python…
Input
log=["login", "view", "buy", "view", "logout"], left="buy", right="view"
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.