Google Interview Question


Country: United States




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

Roughly O(nm) complexity and O(nm) memory where n is the number of Strings and m is the length of the Strings.

public static int countAnagramSets(String[] strArr){
    int count = 0;
    HashSet<String> anagramSignatures = new HashSet<String>();
    for(String str : strArr){
        String signature = getSignature(str);
        if(!anagramSignatures.contains(signature)){
            count++;
            anagramSignatures.add(signature);
        }
    }
    return count;
}

private static String getSignature(String str){
    //assuming default character set

    //count each instance of a character in the string
    int[] charCount = new int[26];
    for(char c : str.toCharArray()){
        charCount[(int)c - (int)'a']++;
    }

    //build a suitable signature
    StringBuilder builder = new StringBuilder();
    for(int i = 0; i < charCount.length; i++){
        if(charCount[i] > 0){
            builder.append((char)(i + (int)'a'));
            builder.append(Integer.toString(charCount[i]);
        }
    }
    return builder.toString();
}

- zortlord June 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Signature is not needed; hashcode would suffice

- Yev July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

hashcode for "abc" is 96354 but for "cab" is 98244.

- tqjustc July 02, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And why not summing the hashcode of each character of the string in order to have the same hashcode for two anagrams ? Something like :

static int NumberofAnagrams(LinkedList<String> l){
		if (l==null || l.isEmpty()){
			return 0;
		}
		else{
			HashSet H = new HashSet();
			while(!l.isEmpty()){
				String s = l.pop();
				int t = hach(s);
				if (!H.contains(t)){
					H.add(t);
				}
			}
			return H.size();
		}
	}
	
	static int hach(String s){
		if (s==null || s.length()==0) return 0;
		int p = 0;
		for (int k = 0; k<s.length(); k++){
			String c = String.valueOf(s.charAt(k));
			p += c.hashCode();
		}
		return p;
	}

- jv July 02, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And why not summing the hashcode of each character to determine the one of the string in order to avoid the problem of different hashcodes for two anagrams ?
It would give something like this :

static int NumberofAnagrams(LinkedList<String> l){
		if (l==null || l.isEmpty()){
			return 0;
		}
		else{
			HashSet H = new HashSet();
			while(!l.isEmpty()){
				String s = l.pop();
				int t = hach(s);
				if (!H.contains(t)){
					H.add(t);
				}
			}
			return H.size();
		}
	}
	
	static int hach(String s){
		if (s==null || s.length()==0) return 0;
		int p = 0;
		for (int k = 0; k<s.length(); k++){
			String c = String.valueOf(s.charAt(k));
			p += c.hashCode();
		}
		return p;
	}

- jv July 02, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And why not summing the hashcode of each character to determine the one of the string in order to avoid the problem of different hashcodes for two anagrams ?
It would give something like this :

static int NumberofAnagrams(LinkedList<String> l){
		if (l==null || l.isEmpty()){
			return 0;
		}
		else{
			HashSet H = new HashSet();
			while(!l.isEmpty()){
				String s = l.pop();
				int t = hach(s);
				if (!H.contains(t)){
					H.add(t);
				}
			}
			return H.size();
		}
	}
	
	static int hach(String s){
		if (s==null || s.length()==0) return 0;
		int p = 0;
		for (int k = 0; k<s.length(); k++){
			String c = String.valueOf(s.charAt(k));
			p += c.hashCode();
		}
		return p;
	}

- jv July 02, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class Anagrams {

	public Anagrams() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Anagrams ax = new Anagrams();
		String str;
		try {
			str = br.readLine();
			int t = Integer.parseInt(str);

			String[] xargs = null;
			while (t-- > 0) {
				str = br.readLine();
				xargs = str.split(",");
				ax.doIt(xargs.length);
				for (int i = 0; i < xargs.length; i++) {
					ax.map(xargs[i], i);
				}
				// ax.deepToString(ax.a);
			}
			ax.hash(ax.a, xargs);
			System.out.println(ax.map);
			System.out.println(ax.map.size());
		} catch (IOException e) {

		}
		br.close();
	}

	public void doIt(int n) {
		a = new int[n][26];
	}

	int[][] a = null;

	public void map(String s, int j) {
		a[j] = new int[26];
		for (int i = 0; i < s.length(); i++) {
			if (a[j][atoi(s.charAt(i))] == 0)
				a[j][atoi(s.charAt(i))] = 1;
			else
				a[j][atoi(s.charAt(i))] = a[j][atoi(s.charAt(i))] + 1;
		}
	}

	public int atoi(char ch) {
		int x = (int) ch;
		if (x >= 65 && x <= 90)
			return x - 65;
		if (x >= 97 && x <= 122)
			return x - 97;
		return -1;
	}

	HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();

	public void hash(int[][] a, String[] xargs) {
		for (int i = 0; i < a.length; i++) {
			int sum = 0;
			for (int j = 0; j < a[i].length; j++) {
				if (a[i][j] != 0) {
					sum += a[i][j] * Math.pow(3, j + 1);
					sum = (sum % 1000007);
				}
			}
			if (sum != 0 && map.get(sum) != null) {
				map.get(sum).add(xargs[i]);
			} else {
				map.put(sum, new ArrayList<String>());
				map.get(sum).add(xargs[i]);
			}
		}
	}

	public void deepToString(Object... objects) {
		System.out.println(Arrays.deepToString(objects));
	}

}

- Sheetal July 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class Anagrams {

public Anagrams() {
// TODO Auto-generated constructor stub
}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Anagrams ax = new Anagrams();
String str;
try {
str = br.readLine();
int t = Integer.parseInt(str);

String[] xargs = null;
while (t-- > 0) {
str = br.readLine();
xargs = str.split(",");
ax.doIt(xargs.length);
for (int i = 0; i < xargs.length; i++) {
ax.map(xargs[i], i);
}
// ax.deepToString(ax.a);
}
ax.hash(ax.a, xargs);
System.out.println(ax.map);
System.out.println(ax.map.size());
} catch (IOException e) {

}
br.close();
}

public void doIt(int n) {
a = new int[n][26];
}

int[][] a = null;

public void map(String s, int j) {
a[j] = new int[26];
for (int i = 0; i < s.length(); i++) {
if (a[j][atoi(s.charAt(i))] == 0)
a[j][atoi(s.charAt(i))] = 1;
else
a[j][atoi(s.charAt(i))] = a[j][atoi(s.charAt(i))] + 1;
}
}

public int atoi(char ch) {
int x = (int) ch;
if (x >= 65 && x <= 90)
return x - 65;
if (x >= 97 && x <= 122)
return x - 97;
return -1;
}

HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();

public void hash(int[][] a, String[] xargs) {
for (int i = 0; i < a.length; i++) {
int sum = 0;
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
sum += a[i][j] * Math.pow(3, j + 1);
sum = (sum % 1000007);
}
}
if (sum != 0 && map.get(sum) != null) {
map.get(sum).add(xargs[i]);
} else {
map.put(sum, new ArrayList<String>());
map.get(sum).add(xargs[i]);
}
}
}

public void deepToString(Object... objects) {
System.out.println(Arrays.deepToString(objects));
}

}

- Sheetal July 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Calculate hash of each of the string using a hash functions that does not take the position of character into account. Answer is number of distinct hash values obtained.

Assuming the string has only small case alphabets you can use calculate charCount[26] for each of the string i.e. count of each alphabet considering 'a' is mapped to position 0 in charCount. Answer will be number of distinct charCount arrays generated. Complexity will be O(n*m*26) where n is number of strings, m is string length.

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

What would be the hash formula in this case?

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

@rakhee63 Assign a prime number to every character and the hashcode will be the product of letters corresponding prime numbers.

For example:

Assign a = 2, b = 3, c = 5, d = 7 etc,.

"aa" = 2 * 2 = 4
"abc" = 2 * 3 * 5 = 30
"bac" = 3 * 2 * 5 = 30
"cab" = 5 * 2 * 3 = 30

Problem: Integer/Long overflow!

- Virupaksha Swamy October 19, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int anagramSet(List<String> list){
if(list == null){
return 0;
}
Set<String> set = new HashSet<String>();
for(String str:list){

char[] arr = str.toCharArray();
Arrays.sort(arr);
String sorted = String.valueOf(arr);
set.add(sorted);
}
return set.size();
}

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

What would be the hash formula in this case?

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

This might sound silly, but can anyone help me understand
how the original question found 5 sets of anagrams:

Set: <abc,cab,dac,beed,deb,few,acd>
Anagrams:
abc, cab
dac, acd
deb, beed
So 3 sets of anagrams, not 5?

- puneet.sohi June 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

deb and beed are not anagrams, so they belong to separate sets. Two strings are an anagram if they have the same count of each character. beed has one more 'e' than deb so they are not anagrams.

Also you forgot few. So there you go - 5 sets of anagrams.

- 010010.bin June 30, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

how is it five sets?

- Phoenix July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

what is the set of anagrams because as per above program the set cantain : a1b1c1,a1c1d1,b1d1e2,b1d1e1,e1f1w1

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

Ruby impl. Running time: O(n*m*logm). Space:O(n).

require 'set'

def anagrams_count(array)
  return 0 if array.nil? || !array.kind_of?(Array) || array.length == 0
  
  anagrams_set=Set.new
  
  array.each do |str|
    sorted_str=str.chars.sort.join
    anagrams_set.add(sorted_str)
  end
  
  anagrams_set.size
end


require_relative '../../../src/anagrams'

describe 'anagrams' do
  context 'error input: []' do
    let(:strings){[]}
    
    it 'shall return blank' do
      expect(anagrams_count(strings)).to eq(0) 
    end
  end
  
  context 'error input: nil' do
    let(:strings){nil}
    
    it 'shall return blank' do
      expect(anagrams_count(strings)).to eq(0) 
    end
  end
  
  context 'error input: string' do
    let(:strings){'hello'}
    
    it 'shall return blank' do
      expect(anagrams_count(strings)).to eq(0) 
    end
  end
  
  context 'valid input' do
    let(:strings){['abc','cab','dac','beed','deb','few','acd']}
    
    it 'shall return anagrams' do
      expect(anagrams_count(strings)).to eq(5)
    end
  end
end

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

Memory is O(mn) due to allocating new string

- Yev July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Looking at an alternative solution... Sorting is unnecessary because each element is accessed at least once and position doesn't add value to the anagram hashcode.

- Yev July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Explain how is it 5 sets of anagrams?

- Phoenix July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

there is a typo in the question.
'beed' should have been 'bed'. Hope that helps :)

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

Dude,
Anagram means both the strings should have same set of alphabets and same number of types each alphabet should appear.

in above example

abc,bca -- have same alphabets a,b,c and appear same number of times in each string

dac,acd -- alphabets a,c,d and appear same number of times in each string

deb,beed are belong to two different sets because in 1st string b -1 e -1 d-1 but in 2nd string b -1 e-2 d-1

few --

So total 5 sets

- cnu1438 July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry dude, even I missed two strings.
My Code:
Please let me know if any thing wrong in this

package com.cnu.ds.programs;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class SetOfAnagrams {

	public int count(List<String> list) {
		List<Set<String>> sets = new LinkedList<>();
		boolean isNotPresent = false;
		for (String string : list) {
			for (Set<String> set : sets) {
				String anagram = set.iterator().next();
				if (anagrams(string, anagram)) {
					set.add(string);
					isNotPresent = true;
					break;
				}
			}
			System.out.println(isNotPresent+" "+sets+"  "+string);
			if (!isNotPresent) {
				Set<String> set = new HashSet<>();
				set.add(string);
				sets.add(set);
			}
			isNotPresent = false;
		}
		System.out.println(sets);
		return sets.size();
	}

	public boolean anagrams(String s1, String s2) {
		if (s1 != null && s2 != null) {
			if (s1.length() == s2.length()) {
				int[] noOfAlphabetsInS1 = new int[26];
				for (int i = 0; i < s1.length(); i++) {
					noOfAlphabetsInS1[s1.charAt(i) - 97]++;
					noOfAlphabetsInS1[s2.charAt(i) - 97]--;
				}
				for (int i = 0; i < noOfAlphabetsInS1.length; i++) {
					if (noOfAlphabetsInS1[i] != 0) {
						return false;
					}
				}
				return true;
			}
		}
		return false;
	}

	public static void main(String[] args) {
		// String a = "bed";
		// String b = "bee";
		// System.out.println(String.format("%s and %s are %s anagrams", a, b,
		// anagrams(a, b) ? "" : "not"));

		String[] strings = { "abc", "cab", "dac", "bed", "few", "deb","acd" };
		String[] strs={"xyz","abc"};
		SetOfAnagrams anagrams = new SetOfAnagrams();
		System.out.println("Total Number of sets of Anagrams: "
				+ anagrams.count(Arrays.asList(strs)));
	}
}

- cnu1438 July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Ignore my comment.

Please check my code and let me know if anything is wrong

package com.cnu.ds.programs;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class SetOfAnagrams {

	public int count(List<String> list) {
		List<Set<String>> sets = new LinkedList<>();
		boolean isNotPresent = false;
		for (String string : list) {
			for (Set<String> set : sets) {
				String anagram = set.iterator().next();
				if (anagrams(string, anagram)) {
					set.add(string);
					isNotPresent = true;
					break;
				}
			}
			System.out.println(isNotPresent+" "+sets+"  "+string);
			if (!isNotPresent) {
				Set<String> set = new HashSet<>();
				set.add(string);
				sets.add(set);
			}
			isNotPresent = false;
		}
		System.out.println(sets);
		return sets.size();
	}

	public boolean anagrams(String s1, String s2) {
		if (s1 != null && s2 != null) {
			if (s1.length() == s2.length()) {
				int[] noOfAlphabetsInS1 = new int[26];
				for (int i = 0; i < s1.length(); i++) {
					noOfAlphabetsInS1[s1.charAt(i) - 97]++;
					noOfAlphabetsInS1[s2.charAt(i) - 97]--;
				}
				for (int i = 0; i < noOfAlphabetsInS1.length; i++) {
					if (noOfAlphabetsInS1[i] != 0) {
						return false;
					}
				}
				return true;
			}
		}
		return false;
	}

	public static void main(String[] args) {
		// String a = "bed";
		// String b = "bee";
		// System.out.println(String.format("%s and %s are %s anagrams", a, b,
		// anagrams(a, b) ? "" : "not"));

		String[] strings = { "abc", "cab", "dac", "bed", "few", "deb","acd" };
		String[] strs={"xyz","abc"};
		SetOfAnagrams anagrams = new SetOfAnagrams();
		System.out.println("Total Number of sets of Anagrams: "
				+ anagrams.count(Arrays.asList(strs)));
	}
}

- cnu1438 July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<set>
#include<vector>

using namespace std;

int main(){

string collec[] = {"abc","cab","dac","beed","deb","few","acd"};
vector<string> strvec(collec, collec+7);
vector<string>::iterator it = strvec.begin();
set<int> elements;
while(it != strvec.end()){
string input = *it;
int sum=0;
for(string::iterator its=input.begin();its!=input.end();its++){
sum += int(*its);
}
elements.insert(sum);
++it;
}
cout<<"count:"<<elements.size();
}

- Anonymous July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

That looks wrong. Try with

string collec[] = {"ad","cb"};

- Eugen August 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<set>
#include<vector>

using namespace std;

int main()

string collec[] = {"abc","cab","dac","beed","deb","few","acd"};
    vector<string> strvec(collec, collec+7);
    vector<string>::iterator it = strvec.begin();
    set<int> elements;
    while(it != strvec.end()){
        string input = *it;
        int sum=0;
        for(string::iterator its=input.begin();its!=input.end();its++){
            sum += int(*its);
            //elements.insert(sum);
        }
        elements.insert(sum);
        ++it;
    }
    cout<<"count:"<<elements.size();
    int c;
    cin>>c;

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

#include<iostream>
#include<set>
#include<vector>

using namespace std;

int main(){

string collec[] = {"abc","cab","dac","beed","deb","few","acd"};
vector<string> strvec(collec, collec+7);
vector<string>::iterator it = strvec.begin();
set<int> elements;
while(it != strvec.end()){
string input = *it;
int sum=0;
for(string::iterator its=input.begin();its!=input.end();its++){
sum += int(*its);
//elements.insert(sum);
}
elements.insert(sum);
++it;
}
cout<<"count:"<<elements.size();
int c;
cin>>c;
}

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

#include<iostream>
#include<set>
#include<vector>

using namespace std;

int main(){

string collec[] = {"abc","cab","dac","beed","deb","few","acd"};
vector<string> strvec(collec, collec+7);
vector<string>::iterator it = strvec.begin();
set<int> elements;
while(it != strvec.end()){
string input = *it;
int sum=0;
for(string::iterator its=input.begin();its!=input.end();its++){
sum += int(*its);
//elements.insert(sum);
}
elements.insert(sum);
++it;
}
cout<<"count:"<<elements.size();
int c;
cin>>c;
}

- sk July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<set>
#include<vector>

using namespace std;

int main(){

    string collec[] = {"abc","cab","dac","beed","deb","few","acd"};
    vector<string> strvec(collec, collec+7);
    vector<string>::iterator it = strvec.begin();
    set<int> elements;
    while(it != strvec.end()){
        string input = *it;
        int sum=0;
        for(string::iterator its=input.begin();its!=input.end();its++){
            sum += int(*its);
            //elements.insert(sum);
        }
        elements.insert(sum);
        ++it;
    }
    cout<<"count:"<<elements.size();
    int c;
    cin>>c;
}

- sk July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <string>
using namespace std;

int main()
{
uint32_t i;
std::string tmp;

std::vector<std::string> str = {"abccd", "efgh", "hytr", "yincec", "ccdba", "cdcba", "yucybd", "hgfe", "ghfe"};
//std::string *str = new std::string[10];

std::vector<std::string>::iterator it;

std::hash<std::string> hash_fn;

size_t hash_str[str.size()];

typedef std::list<int> lint;

std::map<size_t,lint> aMap;

for (it = str.begin(), i=0; it!=str.end(); ++it, i++)
{
tmp = *it;

std::sort(tmp.begin(), tmp.end());

hash_str[i] = hash_fn(tmp);

aMap[hash_str[i]].push_back(i);
}

cout << endl;

for (std::map<size_t,lint>::iterator ait=aMap.begin(); ait !=aMap.end(); ++ait)
{
for(lint::iterator lit = (*ait).second.begin(); lit != (*ait).second.end() ;++lit)
cout << str[*lit] << "\t";

cout << endl;
}

return 0;
}

- Sandeep July 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <string>
using namespace std;

int main()
{
	uint32_t i;
	std::string tmp;

	std::vector<std::string> str = {"abccd", "efgh", "hytr", "yincec", "ccdba", "cdcba", "yucybd", "hgfe", "ghfe"};
	//std::string *str = new std::string[10];

	std::vector<std::string>::iterator it;

	std::hash<std::string> hash_fn;

	size_t hash_str[str.size()];

	typedef std::list<int> lint;

	std::map<size_t,lint> aMap;

	for (it = str.begin(), i=0; it!=str.end(); ++it, i++)
	{
		tmp = *it;

		std::sort(tmp.begin(), tmp.end());

		hash_str[i] = hash_fn(tmp);
		
		aMap[hash_str[i]].push_back(i);
	}
		
	cout << endl;

	for (std::map<size_t,lint>::iterator ait=aMap.begin(); ait !=aMap.end(); ++ait)
	{
		for(lint::iterator lit = (*ait).second.begin(); lit != (*ait).second.end() ;++lit)
			cout << str[*lit] << "\t";

		cout << endl;
	}

	return 0;
}

- Sandeep July 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <string>
using namespace std;

int main()
{
	uint32_t i;
	std::string tmp;

	std::vector<std::string> str = {"abccd", "efgh", "hytr", "yincec", "ccdba", "cdcba", "yucybd", "hgfe", "ghfe"};
	//std::string *str = new std::string[10];

	std::vector<std::string>::iterator it;

	std::hash<std::string> hash_fn;

	size_t hash_str[str.size()];

	typedef std::list<int> lint;

	std::map<size_t,lint> aMap;

	for (it = str.begin(), i=0; it!=str.end(); ++it, i++)
	{
		tmp = *it;

		std::sort(tmp.begin(), tmp.end());

		hash_str[i] = hash_fn(tmp);
		
		aMap[hash_str[i]].push_back(i);
	}
		
	cout << endl;

	for (std::map<size_t,lint>::iterator ait=aMap.begin(); ait !=aMap.end(); ++ait)
	{
		for(lint::iterator lit = (*ait).second.begin(); lit != (*ait).second.end() ;++lit)
			cout << str[*lit] << "\t";

		cout << endl;
	}

	return 0;
}

- sandeep July 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <string>
using namespace std;

int main()
{
	uint32_t i;
	std::string tmp;

	typedef std::vector<std::string> vstring;
	vstring str = {"abccd", "efgh", "hytr", "yincec", "ccdba", "cdcba", "yucybd", "hgfe", "ghfe"};

	vstring::iterator it;

	std::hash<std::string> hash_fn;

	size_t hash_str[str.size()];

	typedef std::list<int> lint;
	std::map<size_t,lint> aMap;

	for (it = str.begin(), i=0; it!=str.end(); ++it, i++)
	{
		tmp = *it;

		std::sort(tmp.begin(), tmp.end() );

		hash_str[i] = hash_fn(tmp);
		
		aMap[hash_str[i]].push_back(i);
	}
	
	for (std::map<size_t,lint>::iterator ait=aMap.begin(); ait !=aMap.end(); ++ait)
	{
		for(lint::iterator lit = (*ait).second.begin(); lit != (*ait).second.end() ;++lit)
			cout << str[*lit] << "\t";

		cout << endl;
	}

	return 0;
}

- sandeep July 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <string>
using namespace std;

int main()
{
uint32_t i;
std::string tmp;

typedef std::vector<std::string> vstring;
vstring str = {"abccd", "efgh", "hytr", "yincec", "ccdba", "cdcba", "yucybd", "hgfe", "ghfe"};

vstring::iterator it;

std::hash<std::string> hash_fn;

size_t hash_str[str.size()];

typedef std::list<int> lint;
std::map<size_t,lint> aMap;

for (it = str.begin(), i=0; it!=str.end(); ++it, i++)
{
tmp = *it;

std::sort(tmp.begin(), tmp.end() );

hash_str[i] = hash_fn(tmp);

aMap[hash_str[i]].push_back(i);
}

for (std::map<size_t,lint>::iterator ait=aMap.begin(); ait !=aMap.end(); ++ait)
{
for(lint::iterator lit = (*ait).second.begin(); lit != (*ait).second.end() ;++lit)
cout << str[*lit] << "\t";

cout << endl;
}

return 0;
}

- sandeep July 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
public class id5639359996887040
{
	public static void main(String[] args)
	{
		ArrayList<String> myList = new ArrayList<String>();
		myList.add("abc"); myList.add("cab"); myList.add("dac");
		myList.add("beed"); myList.add("deb"); myList.add("few");
		myList.add("acd");
	
		HashSet<String> mySet = new HashSet<String>();
		for (int i = 0; i < myList.size(); i ++)
		{
		    char[] charArr = myList.get(i).toCharArray();
		    Arrays.sort(charArr);
            mySet.add(new String(charArr));
		}
		System.out.println("size: " + mySet.size());
	}

}

- tqjustc July 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

with sorting used, isn't this algorithm slightly slower? mnlog(n)

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

Since only alphabets are considered for anagrams. Find hash for each string using hash formula as ascii sum of characters in string

def anagrams(input_list):
	hash_list = {}
	for inp in input_list:
		total_val = 0
		for ch in inp:
			ascii_val = ord(ch)
			if (ascii_val > 96 and ascii_val < 122) or (ascii_val > 65 and ascii_val < 90):
				total_val += ascii_val

		hash_list[total_val] = hash_list.get(total_val, [])
		hash_list.get(total_val, []).append(inp)
	print hash_list
	print len(hash_list.keys())

- Subramaniam July 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this is incorrect as you cannot guarantee the sum of ascii values to be unique

- vivekh September 06, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

1. parse each string in a given set and sort them
2. Insert each string into a trie
3. count the total number of paths in the trie, this will be the number of unique sets

eg i/p = { abc, cab, dac, beed, deb, few, acd }
sorted o/p = {abc, abc, adc, bdee, bde, efw, adc}
after inserting in trie we get following unique paths( root to leaf)
{ abc, adc, bdeem bde, efw}

return the count of unique paths

- vivekh September 06, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

>>> def anagrams(input_list):
	hash_list = {}
	for inp in input_list:
		total_val = 0
		for ch in inp:
			ascii_val = ord(ch)
			if (ascii_val > 96 and ascii_val < 122) or (ascii_val > 65 and ascii_val < 90):
				total_val += ascii_val

		hash_list[total_val] = hash_list.get(total_val, [])
		hash_list.get(total_val, []).append(inp)
	print hash_list
	print len(hash_list.keys())

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

import java.util.ArrayList;

class MainProg {
ArrayList<String> checkWords = new ArrayList<>();
ArrayList<Integer> numberWords = new ArrayList<>();

public static void main(String[] args) {

ArrayList<String> words = new ArrayList<>();
words.add("abc");
words.add("cab");
words.add("dac");
words.add("beed");
words.add("deb");
words.add("few");
words.add("acd");

MainProg program = new MainProg(words);
program.findasciiNumberforEachSet();
System.out.println(program.NumberofAnagrams());
}

public MainProg ( ArrayList<String> words){
checkWords = words;
}

void findasciiNumberforEachSet(){

for (int i = 0; i < checkWords.size(); i++){
numberWords.add(0);
}
for (int i = 0; i < checkWords.size(); i++){
for (int j = 0; j < checkWords.get(i).length(); j++){
int temp = (int)checkWords.get(i).charAt(j);
numberWords.set(i, numberWords.get(i)+ temp);
}
}
}

int NumberofAnagrams (){

for (int i = 0; i < numberWords.size(); i++){
for (int j= i+1 ;j < numberWords.size(); j++){
int x = numberWords.get(i);
int y = numberWords.get(j);

if (x == y){
numberWords.remove(j);
}
}
}
return numberWords.size();
}
}

- steven007132 July 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Use Hashmap to get all the unique counts of strings .
2. Hash function :

	I) assign prime numbers to all the alphabets starting from 3
		a = 3 , b = 5, c = 7, d  = 11 .... till  z
	II) for a given string generate the sum from above sequence 
		eg. for abc = 3+5+7 = 15
		      for bca = 5+7+3 = 15
		
	III) for hash function string sum(generated above) is the output.

- Source July 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

That looks wrong. Note that 5+11 = 3 + 13...

- Eugen August 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int result = 0;
String[] words = new String[]{"abc", "cab", "dac", "beed", "deb", "few", "acd", "silent", "listen"};
Set<String> values = new HashSet<>();
for (String word : words) {
char[] c = word.toCharArray();
Arrays.sort(c);
if (values.add(new String(c))) {
result++;
}
}
System.out.println(result);

- tavyy August 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int result = 0;
String[] words = new String[]{"abc", "cab", "dac", "beed", "deb", "few", "acd", "silent", "listen"};
Set<String> values = new HashSet<>();
        for (String word : words) {
            char[] c = word.toCharArray();
            Arrays.sort(c);
            if (values.add(new String(c))) {
                result++;
            }
        }
System.out.println(result);

- tavyy August 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int result = 0;
String[] words = new String[]{"abc", "cab", "dac", "beed", "deb", "few", "acd", "silent", "listen"};
Set<String> values = new HashSet<>();
for (String word : words) {
    char[] c = word.toCharArray();
    Arrays.sort(c);
    if (values.add(new String(c))) {
        result++;
    }
}
System.out.println(result);

- tavyy August 11, 2015 | Flag Reply


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