Skip to content

Instantly share code, notes, and snippets.

@coreyjs
Created February 20, 2021 04:32
Show Gist options
  • Save coreyjs/5e5af3ad2e7463ff3486c55f324acfd4 to your computer and use it in GitHub Desktop.
Save coreyjs/5e5af3ad2e7463ff3486c55f324acfd4 to your computer and use it in GitHub Desktop.
Sparse Arrays - HackerRank
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the matchingStrings function below.
def matchingStrings(strings, queries):
result = []
# this is not an optimal way. Best to store vals in a hashmap
#for q in queries:
# amount = strings.count(q)
# result.append(amount)
hmap = {}
for s in strings:
if s in hmap:
hmap[s] += 1
else:
hmap[s] = 1
for q in queries:
if q in hmap:
result.append(hmap[q])
else:
result.append(0)
return result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
strings_count = int(input())
strings = []
for _ in range(strings_count):
strings_item = input()
strings.append(strings_item)
queries_count = int(input())
queries = []
for _ in range(queries_count):
queries_item = input()
queries.append(queries_item)
res = matchingStrings(strings, queries)
fptr.write('\n'.join(map(str, res)))
fptr.write('\n')
fptr.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment