Problem 270938 · hard · Level 02 Linear Data Structures

Codes One Slip Apart

hash maps · signatures · counting pairs

A warehouse scanner sometimes misreads exactly one character of a shelf code. Two codes are one slip apart if they have the same length and differ in exactly one position (identical codes differ in zero positions, so they are not one slip apart). Given the list codes, return the number of index pairs (i, j) with i < j such that codes[i] and codes[j] are one slip apart. The same code may appear several times; every index counts separately.

Examples

Input:  codes = ["cat", "cot", "cut", "cat", "dog"]
Output: 5
Explanation: cat-cot, cat-cut and cot-cut, plus the second "cat" pairs with cot and cut
(the two "cat" codes are identical and do not count).

Input:  codes = ["ab", "abc", "b"]
Output: 0

Constraints

  • 0 <= len(codes) <= 2 * 10**4
  • 1 <= len(codes[i]) <= 10, lowercase letters and digits.
  • Target complexity: about O(n * L) dictionary work, where L is the code length.

Goals

  • Build a wildcard key for every position of a code
  • Count pairs from group sizes instead of comparing codes
  • Remove the pairs that identical codes add to every key
Starting Python…