Skip to content

Instantly share code, notes, and snippets.

@ricardo1512
Last active February 27, 2024 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardo1512/da7a5bf3ae3d1a99f480a15336e3c361 to your computer and use it in GitHub Desktop.
Save ricardo1512/da7a5bf3ae3d1a99f480a15336e3c361 to your computer and use it in GitHub Desktop.
# https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
def sherlockAndAnagrams(s):
from collections import defaultdict
from math import factorial
# Creating a dictionary of anagrams:
dictionary = defaultdict(lambda: 0)
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
sorted_sequence = sorted(list(s[i:j]))
dictionary["".join(sorted_sequence)] += 1
# Calculating and adding the number of combinations per anagram-item:
combinations = 0
for item, value in dictionary.items():
if value >= 2:
combinations += factorial(value) // (2 * factorial(value - 2))
return combinations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment