Today, I took a coding challenge with this question:Given a List of Strings, write a method removeDuplicates that removes duplicate words from the List and returns an ArrayList of all the unique words. The returned ArrayList should be lexically alphabetically.One thing that I learned while doing this problem is a TreeSet. From my understanding it works like a set but adds elements in order.From the code, I concluded that my time complexity would be O(n).Can anyone offer suggestions or corrections?public static ArrayList<String> removeDuplicates(List<String> input) {    ArrayList<String> array = new ArrayList<String>();    Set<String> noDups = new TreeSet<String>();    if(input.isEmpty()){        return array;    }    if(input.size() == 1){        array.add(input.get(0));        return array;    }    for(int i = 0; i < input.size(); i++){            noDups.add(input.get(i));    }    return new ArrayList<String>(noDups);}
Method that remove duplicates from a list of words in Java
java;object oriented;strings;array;tree
General advicePrefer to declare variables by interfaces and not implementations. You don't need to specify that you use and return an ArrayList, specifying List is enough. So the first lines would be:public static List<String> removeDuplicates(List<String> input) {    List<String> array = new ArrayList<String>();    Set<String> noDups = new TreeSet<String>();ComplexityJavadoc for TreeSet says:This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).Since you are performing a log(n) operation \$n\$ times, this becomes n * log(n).Unnecessary edge casesThis is your main code:for(int i = 0; i < input.size(); i++){        noDups.add(input.get(i));}Now let's take a look at your special cases:if(input.isEmpty()){    return array;}We can see that this would be handled correctly by your main code.Your other special case:if(input.size() == 1){    array.add(input.get(0));    return array;}This too would be handled correctly by your main code.Shortened codeWith the above advice this would shorten your code to:public static List<String> removeDuplicates(List<String> input) {    List<String> array = new ArrayList<String>();    Set<String> noDups = new TreeSet<String>();    for(int i = 0; i < input.size(); i++){        noDups.add(input.get(i));    }    return new ArrayList<String>(noDups);}There is however one more thing we can do, and that is to use a specific constructor of TreeSet: public static List<String> removeDuplicates(List<String> input) {    return new ArrayList<String>(new TreeSet<String>(input));}