[LeetCode] Top Interview 150 Problems Solving # 242 Valid Anagram

Understanding the Problem
It is to find valid anagram. Anagram is a word, as for this problem, which can be rearranged to be formed another word. In this problem, s
and t
strings are given with characters each, and they can form exactly the same words or not. If s
can be rearranged to be t
, or t
can be rearranged to be s
, return True
. If the characters in s
and t
are irrelevant, return False
.
# example 1
Input: s = "anagram", t = "nagaram"
Output: True
# example 2
Input: s = "anagram", t = "annagrmm"
Output: False
Approach
I would solve the problem by simply sorting the two strings and comparing them.
Solution
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 20ms runtime
s_sorted = sorted(s)
t_sorted = sorted(t)
if s_sorted != t_sorted:
return False
return True
This was simple but it took 20ms runtime as the sorting logic used twice in the code was causing a sort of delayed runtime. So I would write down the code again to make it run faster.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 7ms runtime
checked = []
for c in s:
if c in checked:
continue
elif s.count(c) == t.count(c):
checked.append(c)
else:
return False
return True
In this code, it goes into the for
loop by each character as c
. Each character is counted in s
and t
, then compare the count. If counts are equal, put this c
into checked
so the same character will not be considered for checking the count anymore.
This code reduced the runtime by 13ms(20ms → 7ms).
Reflection
Well, I normally do not have to consider the time complexity in easy problems like this, but I would not feel any comfortable with two sorting code lines though. It is better to practice the runtime efficiency for harder problems, I think.
Subscribe to my newsletter
Read articles from Ramhee Yeon directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ramhee Yeon
Ramhee Yeon
South Korean, master's degree of AI. Programmer for LLM, app and web development. I am seeking opportunities to go to the USA and Canada, and Europe. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?