All problems
0504EasyArrayHash Table

Scarce Colour Code

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3471Find the Largest Almost Missing Integer

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A paint line stamps one colour code onto every crate that passes. The array codes lists those stamps in the order the crates went by, and the auditor inspects the line in blocks: a block is any run of k consecutive entries of codes, so there are codes.length - k + 1 blocks in total and blocks may overlap.

A colour code is called scarce when exactly one block contains it. A block contains a code if the code is stamped on at least one of that block's k crates; a block that carries the same code twice still counts as one block.

Return the largest scarce colour code. Every colour code is non-negative, so return -1 when no code is scarce.

Examples

Example 1

Input
codes = [5, 1, 1, 2], k = 2
Output
5

The three blocks are the first two crates, the middle two crates and the last two crates. Code 5 turns up only in the first block and code 2 only in the last, while code 1 turns up in all three, so the largest scarce code is 5.

Example 2

Input
codes = [3, 9, 3], k = 2
Output
-1

The two blocks are the first two crates and the last two crates. Code 3 is carried by both blocks and so is code 9, so nothing is scarce.

Example 3

Input
codes = [12, 50, 4, 50], k = 4
Output
50

The block width matches the number of crates, so there is a single block and it carries all three codes. Each of them is therefore scarce, and 50 is the largest.

Constraints

  • 1 <= codes.length <= 50
  • 0 <= codes[i] <= 50
  • 1 <= k <= codes.length

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def largest_scarce_code(codes: list[int], k: int) -> int:
Java
public int largestScarceCode(int[] codes, int k)
September 7
Apply