MediumPythonJavaScriptTypeScript

Hash Table — First Duplicate

Data StructuresHash TableArrays

Build a hash table from scratch with separate chaining (each bucket is a
list of [key, value] pairs) and use it to find the first element that
appears more than once in an array.

What to implement

class HashTable {
  constructor(size = 32)
  put(key, value)      // insert or update
  get(key)             // → value | undefined
  has(key)             // → boolean
}

solve(arr) must return the first value (by index order) that has already
been seen earlier in the array. Return null if no duplicate exists.

Examples

solve([3, 1, 4, 1, 5, 9, 2, 6, 5])  → 1   // 1 is seen twice first
solve(['a', 'b', 'a', 'c', 'b'])     → 'a'
solve([1, 2, 3])                     → null

Hash function — sum of char codes of String(key) modulo size.

Constraints

  • You must use your own HashTable class, not a native Map or Set, inside

solve.

  • Array elements may be numbers or strings.

Sample tests

Test #1First duplicate is 1 (appears at index 3)
Input: [[3,1,4,1,5,9,2,6,5]]
Output: 1
Test #2String array — "dog" repeats before "cat"
Input: [["cat","dog","bird","dog","cat"]]
Output: "dog"
Test #3All unique — return null
Input: [[1,2,3,4,5]]
Output: null