KatInterview

Tally Unique Words Using Your Own Open-Addressing Table

Data Structure DesignAuto-graded · 23 test cases
MediumAuto-gradedData Structure Designhash-tableopen-addressingstrings

Last updated

Count unique strings in a list by building a custom hash table with probing, without using built-in sets, dictionaries, or similar lookup containers.

You are given a list of strings. Return how many different strings it contains.

Two strings are the same only if they match exactly, character for character. Case matters, and no normalization is applied. The empty string "" is an ordinary value and counts as one distinct string if it appears.

The twist

You must not use built-in hashing containers such as set, dict, frozenset, collections.Counter, or similar ready-made lookup structures. Build the lookup structure yourself. You may use plain lists, strings, and integers.

Your table should:

  • compute a hash value for each string using a function you write,
  • resolve collisions in a way you choose (for example linear probing or chaining),
  • compare the full strings only when needed, such as when two hash values are equal,
  • be sized from the input length so that it stays reasonably sparse.

Task

Implement the function so that it returns the number of distinct strings in the input list.

Constraints

  • 0 <= len(strings) <= 10^6
  • Each string may be empty or of any length; the total number of characters is of a size that fits in memory.
  • Comparison is exact and case-sensitive.
  • An empty list returns 0.
  • If every string is identical, the answer is 1.
  • Built-in sets, dicts, and similar containers must not be used for the lookup.

Examples

Example 1

Input: count_unique_strings(['apple', 'banana', 'apple', 'cherry', 'banana'])

Output: 3

Example 2

Input: count_unique_strings([''])

Output: 1

Example 3

Input: count_unique_strings(['a', 'b', 'c', 'a', 'b'])

Output: 3

Hints

Hint 1

Pick a table capacity that is a power of two and comfortably larger than the number of strings, so that you can map a hash to a slot with a bit mask.

Hint 2

Use open addressing: start at the slot given by the hash, and step forward (wrapping around) until you find either an empty slot or a slot holding the same string.

Hint 3

Store each string's full hash next to it, and compare the hashes first. Only when they match do you compare the actual strings. Increase the counter only when you place a string into an empty slot.