So this is a problem from leetcode. I am given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. I am to return the letter that was added to t.
Here is my solution to the problem:
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
dict_s = {}
dict_t = {}
# loop through string and add the frequency into a dictionary
for i in s:
if i not in dict_s:
dict_s[i] = 1
else:
dict_s[i] += 1
for i in t:
if i not in dict_t:
dict_t[i] = 1
else:
dict_t[i] += 1
# compare the frequency of both dictionaries
for key, value in dict_t.items():
if key not in dict_s:
difference = key
elif value != dict_s[key]:
difference = key
return difference
It says I've used 17.20MB and the runtime was 42MS I know that in everyday coding and practice these numbers are kinda irrelevant but are there any glaring mal practice in my solution that could cause major memory problems in the future if I am working on a project on a grander scale?
You could use one dict instead of two. Count one string, subtract the other.