I was doing an example from Cracking the Coding Interview and I read that executing System.out.println(prefix); (where prefix is a String) would take "O(n) time since each character needs to be printed". If a similar print statement was placed inside a O(1) algorithm (e.g. hash table lookup, etc.) would it make the entire algorithm O(n)?
When describing the big-O complexity of an algorithm, it is crucial to define what the variables in the expression represent. There may often be several! For instance, looking up an integer in a binary tree, then printing the string associated with that node might be characterized as O(m + log n), where n is the number of objects in the tree and m is the length of the string.
It is always an error to use a single variable to represent multiple different factors (e.g, both the number of elements in a hash table and their size), and doing so will result in plainly absurd results (e.g, a hash table lookup being O(n)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With