Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of count function in clojure?

Tags:

clojure

What is the time complexity of count in clojure?

like image 204
unj2 Avatar asked Aug 13 '09 18:08

unj2


1 Answers

Here's the implementation:

public static int count(Object o){
        if(o == null)
                return 0;
        else if(o instanceof Counted)
                return ((Counted) o).count();
        else if(o instanceof IPersistentCollection) {
                ISeq s = seq(o);
                o = null;
                int i = 0;
                for(; s != null; s = s.next()) {
                        if(s instanceof Counted)
                                return i + s.count();
                        i++;
                }
                return i;
        }
        else if(o instanceof String)
                return ((String) o).length();
        else if(o instanceof Collection)
                return ((Collection) o).size();
        else if(o instanceof Map)
                return ((Map) o).size();
        else if(o.getClass().isArray())
                return Array.getLength(o);

        throw new UnsupportedOperationException("count not supported on this type: " + o.getClass().getSimpleName());
}

So it's O(1) for arrays, strings, collections, maps and anything that implements Counted. It's O(n) for anything that implements IPersistentCollection, but not Counted.

like image 154
sepp2k Avatar answered Oct 01 '22 10:10

sepp2k