KatInterview

Count Repeated Strings in a Large List

Arrays & HashingAuto-graded · 20 test cases
EasyAuto-gradedArrays & Hashinghash-mapcountingstrings

Last updated

Tests hash-map frequency counting: find every string occurring more than once in a list and report its count, using exact comparison.

You are given a list of strings, which may contain any Unicode characters, including emoji. Find every string that appears more than once and report how many times it appears.

Task

Implement a function that returns a dictionary mapping each repeated string to its number of occurrences in the list.

Rules

  • Two strings are the same only if they are exactly equal, code point for code point. Do not apply case folding, whitespace trimming, or Unicode normalization. "Apple" and "apple" are different strings, and "é" written as one code point differs from "e" followed by a combining accent.
  • Only strings with a count of at least 2 appear in the result.
  • Strings that appear exactly once are left out.
  • The empty string "" is an ordinary string and follows the same rules.
  • If no string repeats, or the list is empty, return an empty dictionary.
  • The order of keys in the returned dictionary does not matter.

Constraints

  • 0 <= len(items) <= 10^6
  • Each string may be empty and may contain arbitrary Unicode characters.
  • The total input fits in memory.
  • Aim for O(n) expected time, where n is the total size of the input.

Examples

Example 1

Input: repeated_string_counts(['apple', 'banana', 'apple', 'orange', 'banana', 'apple'])

Output: {'apple': 3, 'banana': 2}

Example 2

Input: repeated_string_counts(['hello', 'world', 'hello', '🌍', '🌍'])

Output: {'hello': 2, '🌍': 2}

Hints

Hint 1

A single pass can record how many times each string has been seen. Which data structure gives average O(1) lookups and updates by string?

Hint 2

Count every string first, then keep only the entries whose count is greater than 1. Strings that appear once must not be in the result.

Hint 3

Python strings compare by exact code points, so a dictionary or Counter already treats the strings exactly as the problem requires. No normalization is needed.