I am in the process of learning about big oh notation. For the code below, I have a program that counts the number of words, skipping over the delimiters. For this algorithm, the for loop would be for the length of the sentence and then there is contains that iterates to the string as well. So according to me the the big oh notation for this algorithm would be O(n^3). Is that correct or am I missing something about big Oh notation ?
public class wordCount {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String sentence = "How are you,zak;far: mon. day ?:";
int count = 1;
ArrayList<Character> delim = new ArrayList<Character>();
delim.add(' ');
delim.add(',');
delim.add('.');
delim.add(':');
delim.add(';');
delim.add('"');
delim.add('\'');
for (int i = 0; i != sentence.length() - 1; i++) {
if (delim.contains(sentence.charAt(i))) {
if (!delim.contains(sentence.charAt(i + 1))) {
count++;
}
}
}
System.out.println("The count is: " + count);
}
}
No, you’re not quite right – you’re assuming that the “n” of the O(n) of
containsis the same as the “n” that you’re interested in. It’s not – it’s the length of the array list. In this case, that’s the number of delimiters, not the sentence length.So your algorithm is actually O(N * M) where N is the sentence length and M is the number of delimiters. If you view the set of delimiters as constant with only your sentence as input, your whole algorithm is O(N).
Even though you call
containsconditionally the second time, the total number ofcontainscalls per iteration is only ever 1 or 2 – it can’t grow to (say) the number of delimiters or the size of the sentence.