Determine if two strings/phrases are valid Anagrams | Study Algorithms

preview_player
Показать описание
Two words or phrases are said to be anagrams of each other if they can be formed by re-shuffling of characters in one of them. So if you are given two strings str1 and str2. Write a function to determine if str1 is an anagram of str2.

00:00 - Intro
00:26 - Problem description and test cases
01:57 - Brute Force Solution
03:42 - Optimized approach (Solving in O(n))
06:26 - Dry run of the code

Read More:

💻 Get Social 💻

#studyAlgorithms #programming #interview
Рекомендации по теме
Комментарии
Автор

In the Optimized code, I don't think we need to check for spaces. Since anagrams are supposed to be single words, if there are spaces the string, it will become a phrase instead of a word. Also if we check in the beginning if the strings are of equal length, there is no need for 2 for loops of bucket arrays. The code can be simplified to :

class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;

int counts = new int[26];

for (int i=0; i<s.length(); i++) {
counts [s.charAt(i)-'a']++;
counts [t.charAt(i)-'a']--;
}
for (int count char_counts) {
if (count != 0) {
return false;
}
}
return true;
}
}

also, I don't think we need to convert the string to lower case as it is already given in the problem description that noth strings are lower case.

And shouldn't the space complexity be O(N)? It is a bit confusing.

Just thought I should point it out. Thanks for the clear and concise explanation. I wasn't be able to code this without this video

anirudhv
Автор

Thank you Nikhil for the video. I finally understood. But I still have a question. What is this means : counts[s.charAt(i)-'a']++; I don't understand (arr[]++) array increment is not allowed in Java

feruzayusupova
Автор

Why didn't you used HashMap to fill the values first with key and counter and then to decrement. Why to go for A-Z map?

SatishSingh-ebtq
Автор

instead of bucket array we can use hashtable too right???
by removing spaces

lalanabiridi
Автор

package javaprac;

public class JavaPrac {

public boolean anagram(String str1, String str2){

str1=str1.toLowerCase();
str2=str2.toLowerCase();

str1=str1.replace(" ", "");
str2=str2.replace(" ", "");

int[] arr=new int[26];

for(int i=0;i<str1.length();i++){
arr[str1.charAt(i)-'a']++;
}
for(int i=0;i<str2.length();i++){
arr[str2.charAt(i)-'a']++;
}
for(int count:arr){
if(count!=0)
return false;
}
return true;
}
public static void main(String[] args){
String str1="pRadeep";
String str2="peedrap";
///



////
}
}




what will be the remaining code in main method bee like??

pradeepella
Автор

One more request pls suggest me a book where I can understand advanced java and data structures and algorithms easily

nageshnimmala
Автор

You looped 3 times. Shouldn't this be n^3?

mr_funtor