Skip to main content
Back to problems
Codeforces
Medium
Hash Maps
Strings
Math
Google
Pocket Book

Count how many unordered pairs of words differ in at most one position.

Acceptance 0%
Problem Statement

Problem

You are given several words. Treat two words as a matching pair if they have the same length and differ in at most one character position.

Count how many unordered pairs of distinct words form a matching pair.

A pair of words is unordered, so (i, j) is the same as (j, i).

Notes

  • Words are compared character by character.
  • Only pairs with equal length can match.
  • Two identical words also count as a matching pair.

Goal

Return the number of matching pairs among all distinct word pairs.

Input Format

  • The first line contains an integer nn — the number of words.
  • Each of the next nn lines contains one non-empty word.

Output Format

  • Print one integer: the number of unordered pairs of distinct words that differ in at most one position.

Constraints

  • 1n1051 \le n \le 10^5
  • Word lengths are positive.
  • Total input size is assumed to fit memory/time limits of a typical Codeforces medium problem.
  • Compare only words of the same length.
Examples
Sample cases returned by the problem API.

Example 1

Input

5
aaa
aab
abb
abc
aac

Output

4

Explanation

Matching pairs are: (aaa, aab), (aaa, aac), (aab, abb), and (abb, abc).

Example 2

Input

4
code
code
coda
cope

Output

3

Explanation

Pairs are (code, code), (code, coda), and (code, cope).

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.