KatInterview

Find Non-Overlapping String Pairs by Letter Sets

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationarraysstrings

Last updated

Evaluates efficient character set representation using bit manipulation and frequency-based combinatorial counting.

You are given an array words containing strings made up of lowercase English letters. Your task is to determine how many distinct index pairs (i, j) exist where i < j and the two strings at those positions contain completely different letters—that is, no letter appears in both strings.

Each string in the array is considered independently by its position. If the same string appears multiple times, each occurrence is treated as a separate element. A string with no characters is considered to have no letters, making it compatible with every other string, including other empty strings.

Write a function that returns the total count of such non-overlapping pairs.

Constraints:

  • 1 <= len(words) <= 2000
  • 0 <= len(words[i]) <= 1000
  • Each words[i] contains only lowercase English letters 'a' through 'z'

Examples

Example 1

Input: find_non_overlapping_pairs(['abc', 'def', 'bcd', 'xyz'])

Output: 4

Example 2

Input: find_non_overlapping_pairs(['a', '', 'b', 'a'])

Output: 5

Hints

Hint 1

Think about what information you actually need from each string—does the order or frequency of letters matter?

Hint 2

With only 26 possible letters, you can represent which letters appear in a string using a compact binary encoding.

Hint 3

Two strings share no letters if and only if the bitwise AND of their letter-set representations equals zero.