Describe any operation that takes O(1) time.
The above is pretty much the question (not technically i know) but it's what i've been asked to do. My answer is the following:
An O(1) operation could be to run a loop a constant amount of time, for instance:
Sum = 0;
for (int i = 0; i < 10; i++) { // i<10 runs 11 times, i++ runs 10 times
Sum++; //sum++ runs 10 times
}
The above is an algorithm so no need to be too technical with coding :)
total operation count:
sum = 0; //runs 1 time
for (int i=0; // runs 1 time
i<10; //runs 11 times
i++; //runs 10 times
sum++ //runs 10 times
The algorithm above has O(1)
time complexity because the operations are run constant times. if we were to run the loop n times (e.g. i < n)- where n equals to the amount of elements in the array- the complexity would then be O(N)
because then the loop would run n times meaning the iteration of loop is directly proportional to the data input in array (i know i have not implemented array in the code but this is to just make you think of that approach).
it's not homework or such. I have come to that solution and even tried to work out O(N) complexity...