This is what I am doing:
String one = “some string”
String two = “some string”
I want to know all the characters that are in string one and two and they should come in order as they are in string one
I wrote a Java program which by using Collections performs set operations on both the collection.
What I would like to know that what is the complexity of performing set operations, is it polynomial time or linear time
My program is here
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package careercup.google;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
*
* @author learner
*/
public class CharaterStringsIntersection {
private static final String one = "abcdefgabcfmnx";
private static final String two = "xbcg";
public static void main(String args[]){
List<Character> l_one = new ArrayList<Character>();
List<Character> l_two = new ArrayList<Character>();
for(int i=0; i<one.length(); i++){
l_one.add(one.charAt(i));
}
for(int j=0; j<two.length(); j++){
l_two.add(two.charAt(j));
}
l_one.retainAll(l_two);
Iterator iter = l_one.iterator();
while(iter.hasNext()){
System.out.println(" > " + iter.next());
}
}
}
Output :
run:
> b
> c
> g
> b
> c
> x
Its complexity is O(N * (N + M)), where N =
one.length(), M =two.length().It works in the following way: for each character of
l_one(there are N of them) it scansl_two(sincel_twois anArrayList, scan is linear, so it takes O(M) steps, see [1]) and removes item froml_oneif necessary (removing fromArrayListtakes O(N), see [1]), so you get O(N * (N + M)).You can lower the complexity to O(N * M) by using
LinkedListforl_one(since removing fromLinkedListis O(1), see [2]), and furtherlower it to O(N * log(M)) by using
TreeSetforl_two(since searching inTreeSettakes O(log(M)), see [3]).References:
ArrayListjavadoc)LinkedListjavadoc)add,removeandcontains) (TreeSetjavadoc)