PracticeHashing

First Repeated Report Tag

Easy/MediumHashingtraversalstate trackingset membership Time not estimated Not started

Context

An analytics team reviews tags attached to a report in their recorded order. They need the first tag that appears for a second time, because that is the earliest duplicated label in the report. If every tag is unique, the report passes this check.

Problem

Given a non-empty list of lowercase report tags, scan the tags from left to right. Return the tag at the first position where it has already appeared earlier in the list. If no tag appears twice, return the empty string as the absence marker. The order matters: if several tags repeat, select the one whose second occurrence is encountered first.

Examples

Example 1
Input: tags = ["alpha", "beta", "gamma", "beta", "alpha"]
Output: "beta"
Explanation: The second occurrence of "beta" is encountered before the second occurrence of "alpha", so the executed output is "beta".
Example 2
Input: tags = ["urgent", "finance", "draft", "review"]
Output: ""
Explanation: No tag repeats in the list, so the executed output is the empty string.
Example 3
Input: tags = ["sales", "ops", "sales", "ops", "sales"]
Output: "sales"
Explanation: The second occurrence of "sales" is encountered before the second occurrence of "ops", so the executed output is "sales".

Constraints

  • 1 <= len(tags) <= 100000
  • 1 <= len(tags[i]) <= 30 for every i
  • tags[i]: alphabet lowercase
  • tags[i]: non empty
  • tags contains only lowercase letters in each tag.
  • Types: tags is str[]; result is str

Function signature

def first_repeated_tag(tags: list[str]) -> str
tags list[str]
The report tags in their recorded order; each tag is a non-empty lowercase word.
returns str
The first tag encountered for the second time, or the empty string if all tags are distinct.

Adapted from MBPP problem task_537 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Approved · c024-abs_401_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1