Facebook Interview Question: 1. Given two strings, determi... | Glassdoor

Interview Question

Software Engineering Intern Interview

1. Given two strings, determine whether they are anagrams

 . 2. Given a list of strings, return a list of lists of strings, which represents the list grouping strings by whether they are anagrams of one another.
Answer

Interview Answer

5 Answers

This post has been removed.
Please see our Community Guidelines or Terms of Service for more information.

0

Array of 256 chars for each string. Assign to 0. Then as a character comes increment the count.
Compute a hash key using these 256 values and store the hash key->String mapping.
Do so for each string, if the mapping already exists, add this string to the list of strings for this mapping.

Anonymous on Mar 3, 2016
0

Two strings are anagram if sort(A)=sort(B).
Use HashMap>
The Key will hold the most sorted form of the string and corresponding list will contain its anagrams encountered.
At last just return the list>.

Kedar on Mar 8, 2016
0

Here is a simple unoptimized solution I coded quickly that makes use of a HashMap. The main method just sets up the data and prints the results to check everything is correct. The solution is the 'anagramFinder' method.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main (String[] args) {

        List stringList = new ArrayList();

        stringList.add("abcd");
        stringList.add("abdc");
        stringList.add("acbd");
        stringList.add("acdb");
        stringList.add("xyz");
        stringList.add("xzy");
        stringList.add("wxyz");

        List> finalList = anagramFinder(stringList);

        for (List topList: finalList) {
            for(int i = 0; i > anagramFinder(List stringList) {

        HashMap> anagramMap = new HashMap();

        for (String currentString : stringList) {

            char[] tempCharArray = currentString.toCharArray();
            Arrays.sort(tempCharArray);
            String sortedString = new String(tempCharArray);

            List tempStringList = anagramMap.get(sortedString);

            if (tempStringList == null) {
                tempStringList = new ArrayList();
            }//if

                tempStringList.add(currentString);
                anagramMap.put(sortedString, tempStringList);
        }//for

        return new ArrayList>(anagramMap.values());
    }//anagramFinder
}

Kaconym on Mar 8, 2017
0

For some reason posting the comment cut of a load of code. I have posted the solution over at pastebin instead(if it will allow hyperlinks in comments):

http://pastebin.com/CnUCVha8

pastebin (dot) com (slash) CnUCVha8

Kaconym on Mar 8, 2017

Add Answers or Comments

To comment on this, Sign In or Sign Up.