Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Valid Anagram (easy)
.....
.....
.....
Like the course? Get enrolled and start learning!
A
Anonymous
· 3 years ago
This code passes all the tests however it's wrong as in case of s = "hel" and t = "hll" it returns True
class Solution: def isAnagram(self, s, t): # TODO: Write your code here if len(s) != len(t): return False l = list(s) for c in t: if c not in l: return False return True
Show 1 reply
A
Anonymous
· 3 years ago
function isAnagram(s, t) { // TODO: Write your code here return s.split("").sort().join("") === t.split("").sort().join(""); }
A
Anonymous
· 3 years ago
Your testcases allow the following solution to pass when it should fail. For instance the following are not anagrams {add, ada} but since a Set does not account for the frequency, it passes them as anagrams:
import java.util.Arrays; import java.util.HashSet; import java.util.Set; class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } Set<Character> characters = new HashSet<>(); for (char c : s.toCharArray()) { characters.add(c); } for (char character : t.toCharArray()) { if (!characters.contains(character)) { return false; } } return true; } }
Show 1 reply
A
Anonymous
· 3 years ago
By definition an anagram has to be a word or set of words that can be re-arranged into another word or set of words. An empty string isn't a word and can't be rearranged
Show 1 reply
A
Anonymous
· 3 years ago
class Solution: def isAnagram(self, s, t): # TODO: Write your code here charSet = {} if len(s) != len(t): return False for char in s: if char not in charSet: charSet[char] = 0 else: charSet[char] += 1 for char in t: if char not in charSet: return False else: if charSet[char] >= 0: charSet[char] -= 1 else: return False return True
A
Anonymous
· 3 years ago
class Solution: def isAnagram(self, s, t): # TODO: Write your code here # create dict for string s # check char of t for s dict if it is not in s then false s_dict = {} for ch in s: s_dict[ch] = s_dict.get(ch, 0) + 1 for ch in t: if ch not in s: return False elif ch in s and s_dict[ch] - 1 < 0: return False else: s_dict[ch] -= 1 return True
Reading Progress
0%