Ctrl K

Swapped Initials Names

Hard
You get a list of distinct words words. Double-barrelled names are built from it like this: 1. Pick two different words A and B from the list (order matters: the pair (A, B) differs from (B, A)). 2. Swap their first letters, producing A′ and B′. 3. If neither A′ nor B′ appears in the original list, the string "A′ B′" (the two words joined by a space) is a valid name. Return the number of distinct valid names.
Example 1
words=['moon', 'sun', 'soon'] → 0

Any swap involving "moon" and an s-word turns "moon" into "soon", which is already listed, and swapping "sun" with "soon" changes nothing. So the answer is 0.

Example 2
words=['cat', 'dog', 'bat'] → 4

The pair ("cat", "dog") gives "dat" and "cog", neither of which is listed, so "dat cog" is a name; ("dog", "cat") gives "cog dat". The same works for "bat" with "dog". "cat" and "bat" just turn into each other, so they do not count. That makes 4 names.

Constraints
  • 2 ≤ len(words) ≤ 5·10⁴
  • 1 ≤ len(words[i]) ≤ 10
  • words[i] consists of lowercase English letters
  • All words in words are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWords That Fit Each Puzzle HardLetter Counts of Shortest Covers HardPalindrome After a Few Fixes MediumWords From Working Keys EasyOne New Letter Medium
loading Python…
Input
words=['moon', 'sun', 'soon']
Expected
0

Run checks the first 3 tests in your browser. Submit checks all 26 tests on the server, hidden ones included.