NVIDIA Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
9
of 9 vote

I'll propose another one solution:

final static int LETTERS_LEN = 256;	
	
	public static boolean isAnagram(String s1, String s2) {
		if (s1 == null || s2 == null)
			return false;
		int len = s1.length();
		if (len != s2.length() || len < 2)
			return false;

		int[] letters = new int[LETTERS_LEN];

		for (int i = 0; i < len; i++) {
			letters[s1.charAt(i)]++;
			letters[s2.charAt(i)]--;
		}

		for (int i = 0; i < LETTERS_LEN; i++) {
			if (letters[i] != 0) {
				return false;
			}
		}
		return true;
	}

This solution is based upon the following. When you are scanning first string you are "raising" rate for every letter in hash. In the same (!) loop you are downgrades it for every letter founded in the second string. So, if all letters in the both words will be appeared exactly the same times, their value in hash position must be zero.

And the test for proof:

public class AnagramStringTest {

	private static final String[] in = { "node", "salvador dali", "stream" };
	private static final String[] out = { "done", "avida dollars", "master" };

	@Test
	public void test() {
		assertFalse( foo.bar.StringUtil.isAnagram(null, null));
		assertFalse( foo.bar.StringUtil.isAnagram(null, ""));
		assertFalse( foo.bar.StringUtil.isAnagram("", null));
		assertFalse( foo.bar.StringUtil.isAnagram("", ""));
		assertFalse( foo.bar.StringUtil.isAnagram("1", "2"));
		assertFalse( foo.bar.StringUtil.isAnagram("1", "21234"));
		assertFalse( foo.bar.StringUtil.isAnagram("23", "34"));
		assertFalse( foo.bar.StringUtil.isAnagram("23", "45"));

		for (int i = 0; i < in.length; i++){
			assertTrue( foo.bar.StringUtil.isAnagram(in[i], out[i]));
		}
	}
}

- Vaclav September 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

+1
Solution works out for almost all cases, but length check can make this test case to fail "He bugs Gore" & "George Bush", even though they are anagram if spaces are ignored. I guess this can be question to interviewer.

- Survivor November 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hi Survivor,
Honestly, I don't think the test example you provide is anagram because each phrase has different upper case and lower case. If we change your example all to either lower case or upper case, the answer should be apparently anagram.
If I am wrong, please let me know. Thanks for your example

- Charles April 01, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

you can create a has table with each character as an index. Loop once for first string and set the corresponsing values in hash to 1. Loop again for second string and increment the count for those characters. Third time, go through hash and check the value. If count of each character is 2, then its an anagram..else not.

total complexity is 3n which is O(n)

- Anonymous May 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

anagram strings can have duplicate characters (definition). So midifying your solution:
1.make a hashtable along with counter to each key
2.scan through first string(neglecting white spaces) and increase counter for each character hashed.
3. scan through second string (neglecting white spaces) and decrease counter for each hashed key.
4.scan through hash table . If found any hash counter non zero then "Not a anagram" else "it is"

- Anonymous July 11, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

When u check a hash table with the get() method, it uses a for loop that spans over the entire hashtable. This means that if you have all different characters in your strings in order to increase/decrease counts for both the strings its going to do an O(n(n+1)/2)= O(n^2).
So finally the complexity is O(n^2) +O(n^2) + O(n)= O(n^2)
for first string count + second string count + final check of counts in the hashmap.
Makes sense?

- #Newbie January 19, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The worst case of lookup in hashtable is O(n) while the average case is O(1). So it's fine?

- zyxzyx January 27, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

if a character appears twice in both the strings this will never consider it an anagram

- shiv May 20, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The first answer(amit5624) will work but is NlogN(sort) + N(compare) i.e NlogN overall
The second is just plain wrong! What if you've a repetition of the same character? eg: consider ABBA and BABA...
However, you could tweak it a bit and get the correct result in N.. Look up counting sort/bucket sort.. Of course for this to work, you need to know how the characters are represented(like if it is ASCII etc)
For complete correctness: irrespective of logic you use, you'll definitely have to handle for the character case (and possibly for the presence of non-alphabets)

- code-monkey May 22, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

boolean isAnagram(String s1, String s2){

if(s1==null || s2 ==null)
return false;


int l1=s1.getLength();
int l2=s2.getLength();

if(l1!=l2)
return false;

int i=0;
int j=l2-1;

while(i<j){
if(!s1.charAt(i).equals(s2.charAt(j)))
return false;
}

return true;
}


// test for
(null,null)
("",null)
(null,"")
("","")
("","a")
("A",a)
..
...
...

- Muthukumar May 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

u forgot i,j increment,decrement....secondly,anagrams can be any permutation of a given string not just palindromic...correct me if i am wrong

- mind-boggler July 01, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

boolean isAnagram(String s1, String s2){

if(s1==null || s2 ==null)
return false;

int l1=s1.getLength();
int l2=s2.getLength();

if(l1!=l2)
return false;

// atthis point both are equal length
int i=0;
int j=l2-1;

while(i<=j){
if(!s1.charAt(i).equals(s2.charAt(j)))
return false;
i++;
j--;
}

return true;
}

// test for
(null,null)
("",null)
(null,"")
("","")
("","a")
("A",a)
..
...
...

- Anonymous May 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Arrays;
.....

public boolean isAnagram(String s1, String s2){
     char[] a1 = s1.toCharArray();
     char[] a2 = s2.toCharArray();
		
     Arrays.sort(a1);
     Arrays.sort(a2);
		
     if (Arrays.toString(a1).equals(Arrays.toString(a2))){
          return true;
     }
     return false;
}

- nada June 04, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int anagram(string s1,string s2)
{

- Anonymous July 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Use Count Array
bool anagram2(char *a , char *b)
{
int arr[128] = {0};
while(*a)
{
arr[*a]++;
a++;
}

while(*b)
{
if( arr[*b] == 0)
return 0;
arr[*b]--;
b++;
}
return 1;
}

- Chandra July 26, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This code isnt correct because it will return 1 for substring also. So before returning 1 you should check the length also.

- Alps February 15, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This code isnt correct because it will return 1 for substring also. So before returning 1 you should check the length also.

- Alps February 15, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This code isnt correct because it will return 1 for substring also. So before returning 1 you should check the length also.

- Alps February 15, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public static boolean checkAnagramV2(String str1, String str2){
if(str1.length() != str2.length())
return false;
else{
Integer val1 =0, val2=0;
for (int i=0;i<str1.length();i++)
{
val1 = (str1.charAt(i)-0) ^ val1;
val2 = (str2.charAt(i) -0) ^ val2;
}
if ((val1^val2) == 0)
return true;
else
return false;
}

}

- arpitg February 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Find if two strings are anagrams of eachother.
//Eg. INDIA s an anagram of AIDNI
#include <iostream>
#include <string>
using namespace std;

int main()
{
	cout<<"\t\t CHECK IF THE STRINGS ARE ANAGRAMS";
	string strFirst, strSecond;
	int lenFirst, lenSecond, intCounter;
	intCounter=0;
	bool isAnagram=true;
	cout<<"\n\nEnter the first string: "; getline(cin,strFirst);
	cout<<"\nEnter the second string: "; getline(cin,strSecond);
	lenFirst = strFirst.size();
	lenSecond= strSecond.size();
	//Compare the lengths. FOr the strings to be anagrams the lenghts must be equal
	if(lenFirst!= lenSecond) 
	{
		cout<<"\n\nThese strings are not anagrams as they are of different length"<<endl;
		return 0;
	}
	for(int i=lenSecond-1; i>=0;i--)
	{
		if(strFirst[intCounter] == strSecond[i])
		{
			intCounter++;
			continue;
		}
		else
		{
			cout<<"\nThese strings are not anagrams."<<endl;
			isAnagram=false;
			return 0;
		}
	}
	if(isAnagram)
	{
		cout<<"\nThe string are anagrams";
	}		
}

- nifty August 06, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Bad solution

- Anon September 18, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

To find if two strings are anagrams of each other, all you need to do is sort the strings individually and then compare both the strings. If they are exactly the same, then they are anagrams of each other.

- Pooja January 22, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Not suggested, since time complexity for sort will be atleast O(2nlogn).

- Anonymous August 03, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Not sure why this is a problem. Most of the dictionary words have small value of N. It will be hard to beat a good sort algorithm, IMHO. Also, you could write a bug free code in less than 5 minutes using off the shelf sort and compare, saving your company thousands of dollars in your salary, just kidding. Unfortunately interview questions have a different purpose. So I kind of agree with you.

- manish.baj March 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

bool areAnagrams(char* s1, char* s2)
{
    if (strlen(s1) != strlen(s2))
        return false;

    uchar hist[256];
    memset(hist, 0, 256 * sizeof(uchar));

    for (int i = 0; i < strlen(s1); i++) {
        hist[tolower(s1[i])]++;
        hist[tolower(s2[i])]++;
    }

    for (int i = 0; i < 256; i++)
        if (hist[i] % 2 != 0)
            return false;

    return true;
}

- jtrain March 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is an example where trying to be too clever will bite you..

If s1 = "AA" and s2 = "BB" the histogram will have even counts and incorrectly return TRUE.

- Anonymous July 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>

void main()
{
    char ch[] = "Hello";
    char str[] = "Holle";
    int flag=0;
    int i, j;
    int len1,len2;
    for(len1=0; ch[len1] != '\0';len1++);
    for(len2=0; str[len2]!= '\0';len2++);
    if(len1==len2){
    for(i=0; ch[i] != '\0'; i++)
        for(j=0; str[j] != '\0'; j++){
            if(str[j] == ch[i]){
                str[j]= '1';
            }
        }

    for(i=0; str[i] != '\0';i++)
        if(str[i] == '1')
            flag =1;
        else{
            flag = 0;
            break;
        }
    }
    if(flag)
        printf("Anagrams");
    else
        printf("Not Anagrams");
}

- Napter October 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{

char str1[30],str2[30];
int c1=0,c2=0,c=0,l=0,d=0,i,j;
clrscr();
printf("enter 1st string:");
gets(str1);
printf("enter 2nd string:");
gets(str2);
c1=strlen(str1);
c2=strlen(str2);
if(c1!=c2)
{
printf("not anagram");
}
printf("length%d%d",c1,c2);
for(i=0;i<c1;i++)
{
for(j=0;j<c1;j++)
{
if(str1[i]==str1[j])
{
c++;
}
if(str1[i]==str2[j])
{
d++;
}
}
if(c==d)
{
l++;
}
c=0;
d=0;
}
if(c1==l)
{
printf("the following is anagram");
}
getch();
}

- Anonymous November 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//C#
static bool checkIf2StringsAreAnagrams(string _str1, string _str2)
        {
            bool isAnagrams = false;

            Dictionary<char, int> charset = new Dictionary<char, int>();
            for (int i = 0; i < _str1.Length; i++)
            {
                char key = _str1[i];
                if (!charset.ContainsKey(key))
                {
                    charset.Add(key, 1);
                }
                else
                {
                    charset[key] += 1;
                }
            }

            Dictionary<char, int> charset2 = new Dictionary<char, int>();
            for (int i = 0; i < _str2.Length; i++)
            {
                char key = _str2[i];
                if (!charset2.ContainsKey(key))
                {
                    charset2.Add(key, 1);
                }
                else
                {
                    charset2[key] += 1;
                }
            }

            for (int i = 0; i < charset.Count; i++)
            {
                char key = charset.Keys.ElementAt(i);
                if (charset2.ContainsKey(key))
                {
                    if (charset[key] == charset2[key])
                    {
                        isAnagrams = true;
                    }
                    else
                    {
                        isAnagrams = false; break;
                    }
                }
                else
                {
                    isAnagrams = false; break;
                }
            }
            return (isAnagrams);
        }

- anup.h.nair December 22, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C# solution (modified from book)

public static bool isAnagram(String s, String t)
        {
            if (s == "" || t == "" || s.Length != t.Length)
            {
                return false;
            }

            int[] letters = new int[256];
            char[] s_array = s.ToCharArray();

            foreach (char c in s_array)
            { 
                letters[c]++;
            }

            for (int i = 0; i < t.Length; i++)
            {
                int c = t[i];
                if (--letters[c] < 0)
                {
                    return false;
                }
            }
            return true;
        }

- Anonymous April 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/bin/python

def anagram_checker(str1,str2):
# Use empty dictonary for each string

    dict1={ }
    dict2={ }

    for i in str1:
        dict1[i]=i
    for j in str2:
        dict2[j]=j
# beauty of dictonary - the elements are sorted by itself
    
    if dict1 == dict2:
        print "The strings are anagrams !!"

    else :
        print "Strings are not anagrams !!"

    
anagram_checker('silent','listen')

- python_guy May 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int is_anagram(char *str1, char *str2)
{
int l1 = strlen(str1);
int l2 = strlen(str2);
int s1 = 0, s2 = 0;
int i = 0;

/* if both the string are not equal it is not anagram*/
if(l1 != l2) {
return 0;
}
/* sum up the character in the strings
if the total sum of the two strings is not equal
it is not anagram */
for( i = 0; i < l1; i++) {
s1 += str1[i];
s2 += str2[i];
}
if(s1 != s2) {
return 0;
}
return 1;
}

- Saurabh Bhardwaj September 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can find 26 prime numbers to represent each character (pre-process step). Then define a hash function that will be a multiplication of the characters in the word. where each key corresponds to a prime number. Prime number factorization is guaranteed to be unique, so if 2 words are anagrams of each other - they will both be mapped to the same hash table key.

- supernova May 08, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Anagram
{
public static void main(String args[])
{
String one=new String("ABCD");
String two=new String("cBDA");
if(one.length()==two.length())
{
one = one.toLowerCase();
two = two.toLowerCase();

for(int i=0;i<one.length();i++)
{
char valueOfOne=one.charAt(i);
CharSequence seq = new String(""+valueOfOne);
if(!two.contains(seq))
{
System.out.println("String not matched");
break;
}
System.out.println("String contains "+valueOfOne);

}
}
else
{
System.out.println("length not matching");
}
}
}

- Anonymous June 14, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
  char a[]="table";
  char b[]="belat";
  int i,j=0,flag=0,turn=0,k;
  int len1=strlen(a);
  int len2=strlen(b);
  int c[len1];
  for(i=0;i<len1;i++)
  {
      c[i]=0;
  }
  


if(len1!=len2)
{
 printf("strings are not anagrams\n");
 turn=2;
}
 else
{
 for(i=0;i<len1;i++)
 {
   for(j=0;j<len1;j++)
   {
    if (a[i]==a[j])
     {
     c[i]++;
     }
   }
 }
 

 
 
 for(i=0;i<len1;i++)
  { 
   k=0;
   for(j=0;j<len2;j++)
   {  
    
    if(a[i]==b[j])
      {
      flag=1;
      k++;
      }
    else
      flag=0;
    
    if(flag==1&&k==c[i])
     { 
     flag=1;
     break;
     }
     else 
     { 
     flag=0;
     }

    }
  if(flag==0) 
  { 
  turn=1;
  }
   }
} 
  if(turn==1)
  printf("strings are not anagrams\n");
  if(turn==0)
  printf("strings are anagrams\n");
 
}

- jim June 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

"An anagram is a type of word, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.

For example: orchestra can be rearranged into carthorse or cat can be rearranged into act.

We can find out the anagram strings using below algorithm:

public static boolean isAnagram(String str1, String str2) {
if (str1 == null || str2 == null) {
return false;
} else if (str1.length() != str2.length()) {
return false;
}

Map<Character, Integer> map = new HashMap<Character, Integer>();

for (int i = 0; i < str1.length(); i++) {
char characters = str1.charAt(i);
int charInStr1 = map.containsKey(characters) ? map.get(characters) : 0;
map.put(characters, ++charInStr1);
char charFromStr2 = str2.charAt(i);
int charsInRight = map.containsKey(charFromStr2) ? map.get(charFromStr2) : 0;
map.put(charFromStr2, --charsInRight);
}

for (int occurrences : map.values()) {
if (occurrences != 0) {
return false;
}
}
return true;
}

newtechnobuzzz.blogspot.in/2014/07/check-if-two-strings-are-anagram-in-java.html

- Ashish July 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

why can't we just get the ascii sum of two strings and just compare ?

- nana October 25, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Program
{
static void Main()
{
int flag = 1;
string s1 = Console.ReadLine();
string s2 = Console.ReadLine();
Hashtable has = new Hashtable();
foreach (char c in s1)
{
if (has.ContainsKey(c))
has[c] = Convert.ToInt32(has[c]) + 1;
else
has[c] = 1;

}

foreach (char c in s2)
{
if (has.ContainsKey(c))
{
has[c] = Convert.ToInt32(has[c]) - 1;
}
else
{
flag = 0;
break;
}

}



foreach (DictionaryEntry de in has)
{
if (de.Value.ToString() == "1")
flag = 0;
}

if (flag == 0)
{
Console.WriteLine("Both string are not anagrams of each other");

}
else
{
Console.WriteLine("Both string are anagrams of each other");

}
Console.ReadLine();
}




}

- Vikas January 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Time complexity : O(n)
Space complexity : O(n)

- VIkas January 30, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry Space complexity : O(1)

- Vikas January 30, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class Anagram {

public void validateAnagram(String str1, String str2) {


Set<Character> str11 = new TreeSet<Character>();
Set<Character> str22 = new TreeSet<Character>();

char str111[]=str1.toUpperCase().toCharArray();
char str222[]=str2.toUpperCase().toCharArray();

for(int i=0;i<str111.length;i++)
{
str11.add(str111[i]);
}
for(int i=0;i<str222.length;i++)
{
str22.add(str222[i]);
}


//System.out.println(str11);
//System.out.println(str22);

if(str11.equals(str22))
{
System.out.println("Anagram!");
}
else
{
System.out.println("Not Anagram!");
}
}

public static void main(String[] args) {
Anagram a=new Anagram();
a.validateAnagram("acbed","acbde");
}
}

- Anonymous February 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public boolean isAnagram(String s1, String s2){
if(s1 ==null || s2==null || s1=="" || s2==""){
return false;
}

char[] sc1 = s1.toLowerCase().trim().toCharArray();
char[] sc2 = s2.toLowerCase().trim().toCharArray();

if(sc1.length != sc2.length){
return false;
}

double sum1=0,sum2=0;

for (int i = 0; i < sc2.length; i++) {
sum1+= (sc1[i]-96)*Math.pow(2,(sc1[i]-96));
sum2+= (sc2[i]-96)*Math.pow(2,(sc2[i]-96));
}
if(sum1!=sum2){
return false;
} else {
return true;
}

- praveen June 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isAnagram(String s1, String s2) {
		if (s1 == null || s2 == null || s1 == "" || s2 == "") {
			return false;
		}

		char[] sc1 = s1.toLowerCase().trim().toCharArray();
		char[] sc2 = s2.toLowerCase().trim().toCharArray();

		if (sc1.length != sc2.length) {
			return false;
		}

		double sum1 = 0, sum2 = 0;

		for (int i = 0; i < sc2.length; i++) {
			sum1 += (sc1[i] - 96) * Math.pow(2, (sc1[i] - 96));
			sum2 += (sc2[i] - 96) * Math.pow(2, (sc2[i] - 96));
		}
		if (sum1 != sum2) {
			return false;
		} else {
			return true;
		}

	}

- praveen June 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Anagram {

	public static boolean isAnagram(String s1, String s2) {
		if (s1 == null || s2 == null || s1 == "" || s2 == "") {
			return false;
		}

		char[] sc1 = s1.toLowerCase().trim().toCharArray();
		char[] sc2 = s2.toLowerCase().trim().toCharArray();

		if (sc1.length != sc2.length) {
			return false;
		}

		double sum1 = 0, sum2 = 0;

		for (int i = 0; i < sc2.length; i++) {
			sum1 += (sc1[i] - 96) * Math.pow(2, (sc1[i] - 96));
			sum2 += (sc2[i] - 96) * Math.pow(2, (sc2[i] - 96));
		}
		if (sum1 != sum2) {
			return false;
		} else {
			return true;
		}

	}

}

- praveen June 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

test

- praveen June 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Anagram {

	public static boolean isAnagram(String s1, String s2) {
		if (s1 == null || s2 == null || s1 == "" || s2 == "") {
			return false;
		}

		char[] sc1 = s1.toLowerCase().trim().toCharArray();
		char[] sc2 = s2.toLowerCase().trim().toCharArray();

		if (sc1.length != sc2.length) {
			return false;
		}

		double sum1 = 0, sum2 = 0;

		for (int i = 0; i < sc2.length; i++) {
			sum1 += (sc1[i] - 96) * Math.pow(2, (sc1[i] - 96));
			sum2 += (sc2[i] - 96) * Math.pow(2, (sc2[i] - 96));
		}
		if (sum1 != sum2) {
			return false;
		} else {
			return true;
		}

	}

}

- praveen June 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Anagram {

	public static boolean isAnagram(String s1, String s2) {
		if (s1 == null || s2 == null || s1 == "" || s2 == "") {
			return false;
		}

		char[] sc1 = s1.toLowerCase().trim().toCharArray();
		char[] sc2 = s2.toLowerCase().trim().toCharArray();

		if (sc1.length != sc2.length) {
			return false;
		}

		double sum1 = 0, sum2 = 0;

		for (int i = 0; i < sc2.length; i++) {
			sum1 += (sc1[i] - 96) * Math.pow(2, (sc1[i] - 96));
			sum2 += (sc2[i] - 96) * Math.pow(2, (sc2[i] - 96));
		}
		if (sum1 != sum2) {
			return false;
		} else {
			return true;
		}

	}
}

- praveen June 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java code:
Please give remarks/feedback.
Thanks!

public class Anagram {
	
	public boolean isAnagram(String str1, String str2){
		
		
		char[] array1 = str1.toCharArray();
		char[] array2 = str2.toCharArray();
		
		if(str1.isEmpty() || str2.isEmpty() || str1.length() > 256 || str2.length()>256 || str1.length() != str2.length())
		{
			System.out.println("not an anagram ");
			return false;
		}
	
		for(int j= 0; j< str2.length(); j++){
			int num = str2.length()-j-1;
			if(array1[j] != array2[num]){
				System.out.println("not an anagram in if  ");
				return false;
			}
		}
		
		System.out.println("two string " + str1 +  " & " + str2 + " are anagram of each other ! ");
		return true;
	}
	public static void main(String[] args) {
		
		//anagram of two strings
		Anagram anagram = new Anagram();
		anagram.isAnagram("gjGjgj","jgjgjg" );
	}
}

- akshay talathi October 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Hi, the simplest way to find if two strings are anagrams or not is the following (jus check each character, if yes, replace it with a '\0' as no character array can have a '\0' in the middle) :

public class Test{ 

	public static void main(String args[]){
		String stringa="dedededed frfr";
		String stringb="eeeedddddffrr";
		char[] string1=stringa.toCharArray();
		char[] string2=stringb.toCharArray();
		int count=0;
		if(string1.length != string2.length)
		{
			System.out.println("The two words are not anagram");
		}
		else
		{
			for(int i=0;i<string1.length;i++)
				for(int j=0;j<string2.length;j++)
					if(string1[i] == string2[j])
					{
						string2[j]='\0';
						count++;
						break;
					}
			if(count== string1.length)
				System.out.println("hurray The two words are anagrams :)");
			else
				System.out.println("The two words are not anagram");	  

		}

	}
}

- uma bharati.G May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Test{ 

	public static void main(String args[]){
		String stringa="dedededed frfr";
		String stringb="eeeedddddffrr";
		char[] string1=stringa.toCharArray();
		char[] string2=stringb.toCharArray();
		int count=0;
		if(string1.length != string2.length)
		{
			System.out.println("The two words are not anagram");
		}
		else
		{
			for(int i=0;i<string1.length;i++)
				for(int j=0;j<string2.length;j++)
					if(string1[i] == string2[j])
					{
						string2[j]='\0';
						count++;
						break;
					}
			if(count== string1.length)
				System.out.println("hurray The two words are anagrams :)");
			else
				System.out.println("The two words are not anagram");	  

		}

	}
}

- uma bharati.g May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Another solution to find if two strings are anagrams is the following (just check the string character by character and replace with a ‘\0’ if found same):

public class Test{
public static void main(String args[]){
String stringa=”frfr”;
String stringb=”rrff”;
char[] string1=stringa.toCharArray();
char[] string2=stringb.toCharArray();
int count=0;
if(string1.length != string2.length)
{
System.out.println(“The two words are not anagram”);
}
else
{
for(int i=0;i<string1.length;i++)
for(int j=0;j<string2.length;j++)
if(string1[i] == string2[j])
{
string2[j]='\0';
count++;
break;
}
if(count== string1.length)
System.out.println("hurray The two words are anagrams :)");
else
System.out.println("The two words are not anagram");
}
}
}

- uma bharati.g May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Anagram {

	public static void main(String[] args) {
		String a = "ABCD BC";
		String b = "BCD BAC";
		
		System.out.println(isAnagram(a, b));
		
		
	}
	
	public static  boolean isAnagram(String a, String b){
		if((a !=null && b == null) || (a==null && b !=null)){
			return false;
		}
		if(a == null && b == null){
			return true;
		}
		if(a.equals(b)){
			return true;
		}
		if(a.length() == b.length() && a.length() == 1 && a.equals(b)){
			return true;
		}
		
		String x = a.substring(0,1);
		a = a.substring(1, a.length());
		
		if(b.indexOf(x) > 0){
			b = b.substring(0,b.indexOf(x))+b.substring(b.indexOf(x)+1, b.length());
			return isAnagram(a, b);
		} else {
			return false;
		}
	}

}

- gmhoolageri February 07, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package nvidia;

import java.util.Arrays;

// import org.junit.Assert;

public class CheckAnagrams {
	
	
   public static void main(String[] args){
	   String[][] testcases = { {"anagram", "granmaa" }};
	   
	   for(int i = 0; i < testcases.length; i++){
		   String s1 = testcases[i][0];
		   String s2 = testcases[i][1];
		   
		   boolean res = areAnagrams(s1, s2);
		   System.out.println(s1 + "\t" + s2 + "\t" + res);
	   }
   }

   static boolean areAnagrams(String s1, String s2) {
	   if(s1 == null && s2 == null){
		   return true;
	   } else if (s1 == null || s2 == null){
		   return false;
	   } else if (s1.length() != s2.length()){
		   return false;
	   }
	   
	   int n = s1.length();
		char c1[] = s1.toCharArray();
		Arrays.sort(c1);
		
		char c2[] = s2.toCharArray();
		Arrays.sort(c2);
		
		for(int i = 0; i < n; i++){
			if(c1[i] != c2[i]) {
				return false;
			}
		}
		return true;
	}
}

- just_do_it May 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char in[] = { "salvador dali" }; // , "salvador dali", "stream" };
char out[] = { "avida dollars" };// , "avida dollars", "master" };
char cntin[128];

int isangm(char *s1, char *s2)
{
int indx = 0;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
int sum = 0;

if (s1_len != s2_len)
{
return -1;
}

for (indx = 0; indx < s1_len; indx++)
{
cntin[s1[indx]]++;
cntin[s2[indx]]--;
}
for (indx = 0; indx < s1_len; indx++)
{
sum += cntin[s1[indx]];
}
return sum;
}
int main(int argc, char *argv)
{
int retval = 0;

memset(&cntin[0],0,128);
retval = isangm(&in[0],&out[0],);
if (retval != 0)
{
printf("not an anagram");
}
else
{
printf("An anagram");
}
}

- particlereddy August 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

sort and compare the strings

- camSun April 16, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

workable but bad approach

- abhityagi85 January 05, 2012 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More