简体   繁体   中英

What is the time complexity and space complexity of this algorithm to find Anagrams?

I am working on an interview question from Amazon Software
The question is
"Design an algorithm to take a list of strings as well as a single input string, and return the indices of the list which are anagrams of the input string, disregarding special characters."
I was able to design the algorithm fine, what I did in psuedo code was
1.Create an array character count of the single input string
2.For each string the list, construct the an array character count
3.Compare the character count of each string in list to single output string
4.If same, add it to a list that holds all the indexes of anagrams.
5.Return that list of indices.

Here is my implementation in Java(it works, tested it)

public static List<Integer> indicesOfAnag(List<String> li, String comp){
    List<Integer> allAnas = new ArrayList<Integer>();
    int[] charCounts = generateCharCounts(comp);
    int listLength = li.size();
    for(int c=0;c<listLength; c++ ){ 
        int[] charCountComp = generateCharCounts(li.get(c));
        if(isEqualCounts(charCounts, charCountComp))
            allAnas.add(c);
    }
    return allAnas;
}
private static boolean isEqualCounts(int[] counts1, int[] counts2){
    for(int c=0;c<counts1.length;c++) {
        if(counts1[c]!=counts2[c]) 
            return false;
    }
    return true;
}
private static int[] generateCharCounts(String comp) {
    int[] charCounts = new int[26];
    int length = comp.length();
    for(int c=0;c<length;c++) {
        charCounts[Character.toLowerCase(comp.charAt(c)) - 'a'] ++;
    }
    return charCounts;
}

What I am having trouble with is analyzing the space and time complexity of this algorithm because of both of the sizes of the list and of each string.
Would the time complexity algorithm just be O(N) where N is the size of the list(processing each String once) or do I have to take into account the composite complexity of the length of each String, in that case, O(N * n) where n is the length of the string? I did N * n because you ware processing n N times. And would space complexity be O(N) because I am creating N copies of the 26 length array?

And would space complexity be O(N) because I am creating N copies of the 26 length array?

Yes.

Would the time complexity algorithm just be O(N) where N is the size of the list

No. Time depends on size of input strings, it'll be O(comp.length+sum_of_li_lengths).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM