File: most-frequent-number-following-key-in-an-array/solution.py

Date: 2026-06-06

Time: 18:08

most-frequent-number-following-key-in-an-array/solution.py

Purpose

This file solves LeetCode 2190: given an array nums and a value key, find which number appears most frequently in the position immediately after every occurrence of key. It's a single-function module following the repo's convention of one solution per problem directory.

Key Components

mostfrequentnumberfollowingkeyinan_array(nums, key) — The sole public function. Takes a list of integers and a key integer, returns the integer that most frequently appears at index i+1 whenever nums[i] == key.

The contract: key must appear in nums at least once at a non-terminal position. If it doesn't, counts.most_common(1) will operate on an empty Counter and raise an IndexError.

Patterns

Dependencies

Imports: collections.Counter — used for frequency tracking.

Imported by: most-frequent-number-following-key-in-an-array/test_solution.py directly. The massive "Imported By" list in the repo context is misleading — those are test files for *other* problems that happen to share the same import structure (each test imports its own problem's solution), not actual consumers of this function.

Flow

1. Initialize an empty Counter.

2. Iterate indices 0 through len(nums) - 2.

3. At each index, check if nums[i] == key.

4. If so, increment the count for nums[i + 1].

5. After the loop, return the element with the highest count via most_common(1)[0][0].

The entire operation is O(n) time, O(k) space where k is the number of distinct values following key.

Invariants

Error Handling

None. If key never appears before a non-terminal position, counts stays empty and most_common(1) returns [], causing IndexError on [0][0]. This is acceptable given the LeetCode constraint that guarantees at least one valid occurrence.