Count Pairs Of Similar Strings — LeetCode 2506 Python Solution

EasyBit ManipulationArrayHash TableStringCounting
Problem
#2506
Reading time
2 min

The problem

You are given a 0-indexed string array words. Two strings are similar if they consist of the same characters.

Example

Input
words = ["aba","aabb","abcd","bac","aabc"]
Output
2
Explanation
There are 2 pairs that satisfy the conditions:

Python solution

Python
class Solution:
    def similarPairs(self, words: List[str]) -> int:
        ans = 0
        cnt = Counter()
        for s in words:
            x = 0
            for c in map(ord, s):
                x |= 1 << (c - ord("a"))
            ans += cnt[x]
            cnt[x] += 1
        return ans

Complexity

MeasureComplexity
TimeO(L)
SpaceO(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2506. Count Pairs Of Similar Strings is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2506. Count Pairs Of Similar Strings?
LeetCode 2506. Count Pairs Of Similar Strings is rated Easy on LeetCode.
What is the time complexity of LeetCode 2506. Count Pairs Of Similar Strings?
The Python solution on this page runs in O(L).
What is the space complexity of LeetCode 2506. Count Pairs Of Similar Strings?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2506. Count Pairs Of Similar Strings cover?
LeetCode 2506. Count Pairs Of Similar Strings is tagged Bit Manipulation, Array, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview