String Anagram Solver

The problem at hand involves finding anagrams for a set of queries from a given dictionary of words. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. In this context, the program receives a dictionary of words and a list of queries, and it needs to return the number of anagrams for each query in the dictionary.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the String Anagram Solver from HackerRank using CodeRankGPT:

The solution works by first creating a dictionary where the keys are the sorted version of the words in the dictionary and the values are the counts of these words. This is done because anagrams will have the same sorted version of the word. Then, for each query, it sorts the query and checks if it exists in the dictionary. If it does, it appends the count to the answer list, otherwise it appends 0. This approach leverages the property of anagrams and the fast lookup time of dictionaries in Python.


import math
import os
import random
import re
import sys

from collections import defaultdict

def stringAnagram(dictionary, query):
    d = defaultdict(int)
    for w in dictionary:
        d["".join(sorted(w))] += 1
    ans = []
    for w in query:
        w = "".join(sorted(w))
        ans.append(d[w] if w in d else 0)
    return ans

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    dictionary_count = int(input().strip())

    dictionary = []

    for _ in range(dictionary_count):
        dictionary_item = input()
        dictionary.append(dictionary_item)

    query_count = int(input().strip())

    query = []

    for _ in range(query_count):
        query_item = input()
        query.append(query_item)

    result = stringAnagram(dictionary, query)

    fptr.write('\n'.join(map(str, result)))
    fptr.write('\n')

    fptr.close()

If you have a HackerRank Certification test or a coding interview coming up, you can use CodeRankGPT to your advantage. It will assist you during your test and help ensure you get the certification or the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform