Skip to content

Hashing

Table of Contents

760. Find Anagram Mappings

266. Palindrome Permutation

266. Palindrome Permutation - Python Solution
from collections import defaultdict


# Hash
def canPermutePalindromeDict(s: str) -> bool:
    if len(s) == 1:
        return True

    count = defaultdict(int)

    for ch in s:
        if count[ch] == 1:
            count[ch] = 0
            continue
        count[ch] = 1

    return sum(count.values()) <= 1


# Set
def canPermutePalindromeSet(s: str) -> bool:
    if len(s) == 1:
        return True

    seen = set()

    for ch in s:
        if ch in seen:
            seen.remove(ch)
        else:
            seen.add(ch)

    return len(seen) <= 1


assert canPermutePalindromeDict("carerac") is True
assert canPermutePalindromeSet("carerac") is True

734. Sentence Similarity

734. Sentence Similarity - Python Solution
# Hash Set
def areSentencesSimilar(sentence1, sentence2, similarPairs):
    if len(sentence1) != len(sentence2):
        return False

    sim = set(map(tuple, similarPairs))

    for i in range(len(sentence1)):
        s1, s2 = sentence1[i], sentence2[i]
        if s1 == s2 or (s1, s2) in sim or (s2, s1) in sim:
            continue
        return False

    return True


if __name__ == "__main__":
    sentence1 = ["great", "acting", "skills"]
    sentence2 = ["fine", "drama", "talent"]
    similarPairs = [
        ["great", "fine"],
        ["drama", "acting"],
        ["skills", "talent"],
    ]
    print(areSentencesSimilar(sentence1, sentence2, similarPairs))  # True

1165. Single-Row Keyboard

249. Group Shifted Strings

1133. Largest Unique Number

1426. Counting Elements

1198. Find Smallest Common Element in All Rows

Comments