const arr = ['a','b','c'];
for (let char of arr) {
console.log(char);
}
I believe that time complexity of code above is O(n).
const arr = ['a','b','c'];
for (let char of arr) {
console.log(arr.indexOf(char);
}
However, does indexOf() search all the elements? If does so, I believe time complexity of code above may be O(n^2)
I want to know whether indexOf() searches all the components as for loop or not.
For time complexity, you always consider the worst case (for the OP's circumstance, each character is in the list at no specifically designated position). To take OP example array, doing arr.indexOf('c')
would involve looking at every position until the character c
is found (which is the last position). Therefore, assuming worst case scenario, the execution would take O(n)
time for .indexOf()
. As per @Nick Parsons comment, there are ways to improve the time of the underlying search algorithm using strategies like a binary search (which is O(log n)
time complexity), but that implies the data is in some semi-structured format for any concepts like binary search to improve the time complexity.