Great video! Another edge case to mention is handling leading and trailing white spaces. Before the length check, you should also trim the two strings otherwise "ab " and "ba" won't pass.
@ByteByByte7 жыл бұрын
that's a great point. it would definitely be good to trim first
@iamvikasgola4 жыл бұрын
@@ByteByByte But we are considering all chars in given string. And space is in 256 chars. So we should not trim the strings as that space could be intentional.
@vaibhavkumar383 жыл бұрын
@@iamvikasgola Valid point.. Maybe this could be a clarification question to ask. should we retain leading and traiiling space or should we ignore leading and trailing spaces? Pls share your thoughts!
@oleksandrknyga8686 жыл бұрын
Again, thanks for sharing! It is possible to do an iteration for s1 and s2 in the same array. For longer charspace then 256 I think HashSet would be more preferable.
@wedding_photography5 жыл бұрын
HashMap, not HashSet.
@antonyvilson89736 жыл бұрын
Hi Sam, could you please tell me which is the best book for data structures and algorithms in Java, covering all the algorithms.
@soudiptadutta68866 жыл бұрын
We can use hashmap while solving this problem. The complete code is : class Abc1 { public static void main(String[] args) { String a = "Gini"; //String b = "iGin"; String b = "abcwd"; System.out.println(isAnagram(a,b)); } private static boolean isAnagram(String a, String b) { Map map = new HashMap(); for (int i = 0; i < a.length(); i++) { char ch = a.charAt(i); map.put(ch, map.getOrDefault(ch, 0) +1 ); }//for for (int i = 0; i < b.length(); i++) { char ch = b.charAt(i); if(!map.containsKey(ch)) {return false;} else { int count = map.get(ch); if(count == 0) return false; else {map.put(ch, count -1);} }//else } return true; } }
@Bhavya04097 жыл бұрын
What would be the difference if you used a HashMap to map the count of each character? does a map use more space than an int array of 256 slots? also, is there a benefit to using a for each loop vs a standard for loop, or is it just syntactical sugar?
@ByteByByte7 жыл бұрын
Using a hashmap would be fine, but there is less overhead for an array and it's also just easier to manipulate the content. And theoretically you could use a single loop, but in this case the point is that each loop is iterating over a different string
@Garensonic5 жыл бұрын
Hashmap also has O(n) space complexity but can be adapted to support Unicode characters. The 256 slot int array has constant space.
@bkzlab7 жыл бұрын
Another approach would be to sort both (lowercase) strings or sequences of characters and then check if they (the sorted strings) are the same. Of course, the run time would be N logN (for each sort). Maybe the interviewer would expect you to come up with more than one solutions.
@ByteByByte7 жыл бұрын
Yeah that's certainly another valid approach
@lifeofme31725 жыл бұрын
The last condition could be like if letter.length === 0 then return true (anagram) else false But thanks for the excellent tutorial. Really appreciate it.
@3663johnny5 жыл бұрын
We can also resolve it in constant space complexity by just applying an XOR operation on the asci code of each character in the two string. If we end up with 0 then their anagrams.
@ByteByByte5 жыл бұрын
Does that work in all cases?
@3663johnny5 жыл бұрын
@@ByteByByte I think yes
@wedding_photography5 жыл бұрын
Nope, that's wrong. Try it with "aa" and "bb". Will XOR to zero.
@meghanachitta28474 жыл бұрын
are not supposed to check if the string is null or empty before trying to access its length?? or while converting string to lower case. The above code will throw exception for empty strings.
@remariorichards82375 жыл бұрын
We actually dont need the entire ASCII character set, we can just use the HashMap which would be scoped to the actual letters, also we need to trim
@erichlf6 жыл бұрын
In what world is 1
@ByteByByte6 жыл бұрын
I mean we are literally referring to the number of different combinations of 8 bits... so in this case its because it IS a binary world
@bloonfarmer36575 жыл бұрын
do you need third for loop? Isn’t it do the same thing if can do the checking in the second for loop? If letter[c] is < 0. Return false.
@oceanview-u8q6 жыл бұрын
def anagram1(s1, s2): letters = {} for ch in s1.lower(): if ch not in letters: letters[ch] = 1 else: letters[ch] += 1 for ch in s2.lower(): if ch not in letters: letters[ch] = 1 else: letters[ch] -= 1 for i in letters.values(): if i != 0: return False return True print(anagram1('ABCDE', 'edcba'))
@posamnarmada44994 жыл бұрын
Sir actually thanks for sharing this videos...but a humble request from my side is that would u please explain line by line of what's happening in each line ..sir...it will be helpful for the students like me who are new to programming...
@fernandomederos66896 жыл бұрын
Can someone explain me how can you put a Character in an array of integer I'm kinda confused
@ByteByByte6 жыл бұрын
You aren't putting the characters into the array, you're just counting the number of occurrences of each
@WWEckenman7 жыл бұрын
Wouldn't this version perform better than the one you mentioned? Keep up the good work! public boolean isAnagram(String s1, String s2) { if (s1.length() != s2.length()) return false; int[] letters = new int[256]; for (int i = 0; i < s1.length(); i++) { char c1 = Character.toLowerCase(s1.charAt(i)); char c2 = Character.toLowerCase(s2.charAt(i)); letters[c1]++; letters[c2]--; } for (int i : letters) { if (i != 0) return false; } return true; }
@ByteByByte7 жыл бұрын
Maybe, maybe not. The time complexity is exactly the same either way. Remember that you count time complexity in terms of number of array accesses, so in your example, its N*2 + N, whereas mine is just N + N + N, both of which are O(3N) or O(N)
@MrRys7 жыл бұрын
and if we used something like if(c >= 'A' && c
@BrasilEmFatos4 жыл бұрын
You're so confident that u didn't even ran the code 😂😂 one day wanna be like you
@ndimlo29066 жыл бұрын
sorry, can someone please explain the int[1
@ByteByByte6 жыл бұрын
it creates an array of length 256
@crosscoss6 жыл бұрын
So you take number 1 which in binary is 0 0 0 0 0 0 0 1 (using the representation of an 8 bit/1 byte) and then you shift all the digits to the left ('
@youtubeuseran6 жыл бұрын
@@crosscoss Thank you for the explaination
@mohammadkamran70866 жыл бұрын
Thanks bro.....
@ByteByByte6 жыл бұрын
You're welcome
@tomladdus92644 жыл бұрын
Functional Swift, no worries about ASCII, more memory efficient in most cases: func isAnagram(_ a: String, _ b: String) -> Bool { var dict = a.lowercased().reduce(into: [Character: Int]()) { $0[$1, default: 0] += 1 } dict = b.lowercased().reduce(into: dict) { $0[$1, default: 0] -= 1 } return dict.values.reduce(true) { $0 && $1 == 0 } }
@ranesh2376 жыл бұрын
Is it possible to use dynamic programming here?
@ByteByByte6 жыл бұрын
Yes it's possible, but it wouldn't optimize anything
@rod81284 жыл бұрын
Thanks for the video. Just a typo: In the second loop it should be "char" instead of "chac", right?
@MuteTelecast6 жыл бұрын
Why 256? ASCII has 128 characters.
@ByteByByte6 жыл бұрын
A character in Java is 8 bits, so we're just accounting for every possible character. If you know they're ascii you could do something different
@MirzaTalks365 жыл бұрын
Another solution sort the two strings and check whether equal or not
@dima99175 жыл бұрын
is MotherInLow == WomanHitler tho?
@sateforp7 жыл бұрын
public boolean isAnagram(String s1, String s2) { return si.isEqualIgnoreCase((new StringBuffer(s2)).reverse().toString()) Just reverse one string and compare?
@ByteByByte7 жыл бұрын
I think you're thinking of palindromes. Anagrams can be ordered in any way as long as they have the same number of each character
@huh_wtf6 жыл бұрын
I would suggest an alternative approach you could just sort'em and compare, after converting to lowercase.
@ByteByByte6 жыл бұрын
anotherbuffer account yep there are a bunch of ways you can do this. That being said, what is the complexity of that solution?
@huh_wtf6 жыл бұрын
Byte By Byte It's O(nlogn) coz we're sorting(comparison would take O(n) )....also we could hash the sorted strings and check if they produce the same hash. Couple of ways indeed!
@ByteByByte6 жыл бұрын
Can you sort strings in less than O(nlogn) time?
@sharjeeltahir55836 жыл бұрын
What is anagram? At least explain that before you start.
@oleksandrknyga8686 жыл бұрын
Imagine that you cut off letters from the word and mix them to create a new one. The new word you mixed is an anagram. If you a Harry Portter fan then good example might be I am Lord Voldemort Tom Marvolo Riddle MotherInLow WomanHitler
@joshh.28026 жыл бұрын
It isn't worth spending time on something like that when 90% of the people watching already know what it is, it isn't related to computer science, and it takes 5 seconds to google and find out if you happen to not know. I am personally grateful he doesn't take up a ton of time explaining every possible aspect of each question; let's just see the solution!
@viaprenestina38944 жыл бұрын
video starts at 5 minutes. talk talk
@lmanerich6 жыл бұрын
You could only use 2 for's, in the second one you could check if the letter is 0 before decrement. for (Char c : s2.toCharArray()) { if (letters[c] == 0) return false; letters[c]--; }
@antonyvilson89736 жыл бұрын
Found one method to solve this. Find the ascii value and keep summing, if both sum is equal, then it's anagram. class Anagramtest{ public static void main (String args []) { int sum1=0; int sum2=0; String str1="amazon" ; String str2="amanoz" ; char c; if (str1.length() != str2.length()){ System.out.println("Strings are not anagram") ; return; } for(int i =0;i
@shriduttkothari5 жыл бұрын
yes this should also solve and will reduce one loop
@wedding_photography5 жыл бұрын
That is obviously incorrect. Try it with "ad" and "bc".