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.

Interview Answer

5 Answers

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


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

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

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();


        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();
            String sortedString = new String(tempCharArray);

            List tempStringList = anagramMap.get(sortedString);

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

                anagramMap.put(sortedString, tempStringList);

        return new ArrayList>(anagramMap.values());

Kaconym on Mar 8, 2017

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):


pastebin (dot) com (slash) CnUCVha8

Kaconym on Mar 8, 2017

Add Answers or Comments

To comment on this, Sign In or Sign Up.