r/computerscience • u/Fit-Try9217 • Oct 14 '26
Help Is the best case here O(1)?
Hi, still new to algorithm analysis and need some help confirming my answer or not.
I assumed that best case would be O(1) in this scenario if size of the array is either 0 or 1. But trying to review my answer with online resources, it say's that O(1) doesn't count here?
What is the definite answer here?
EDIT: Hey everyone! Glad everyone got to interact and give responses. The answer was O(N) in the end! Confirmed with my professor.
223
Upvotes
4
u/Fit-Try9217 Oct 14 '26
hey everyone, thanks for the comments so far. I've decided to email my professor to get an elaboration on whether the edge cases (0 and 1) are allowed here.
if anyone would like to know, here are the two questions B and C that followed this question:
(b) How many times is line 12 executed in the best case? In the worst case? Express your answers as functions of n.
(c) Give the Big-O complexity of the function in the best case and in the worst case. Are they different? Explain why.
186
u/JayMKMagnum Oct 14 '26
You're not being asked to pick a value of n. You're being asked to describe how, given a value of n, you could specify an array of size n that achieves the best-case complexity.
So if I asked you "Can you give me an example of an array of 5 elements on which this algorithm achieves its best time? How long does it take?", you wouldn't start going "well an array of zero elements takes constant time".
70
u/SufficientStudio1574 Oct 14 '26
Fuck this font, I read it 10 times and kept getting l and 1 mixed up.
28
u/MistakeIndividual690 Oct 14 '26
This is always O(n) however the fastest time may be when element 0 is the maximum, because you only take the branch once. However it’s possible that it’s not faster at all if it’s compiled to a branch-less assignment
7
u/pi621 Oct 14 '26
To add onto what other people have said
The function inside O describes the relationship between runtime and the value n.
O(1) means the runtime is constant regardless of n.
O(n) means the runtime scales linearly as n increases.
saying something like
"the best case would be O(1) because the array is size 1"
is a fundamental misunderstanding of what big O notation actually means, and you should revise either by yourself or with your professor.
you're essentially saying "Okay so in the best case, this function's runtime is the same for arbitrary size, because if you look at when the size is 0 or 1, the runtime is constant."
Doesn't make a lot of sense, does it?
11
u/rotuami Oct 14 '26
To be really pedantic, the question you pose in the title (what is the big-O complexity of the algorithm) is underspecified. Complexity analysis requires some input and some output. In this case, the implication is "input
nis the size of the list" and "output is the number of instructions". But you could analyze, e.g. the number of assignments tol, and that would give you a different answer.The early return is a distractor, because it's determined by
nand so won't be 0 when the list is empty. The important thing to notice is that the number of steps the loop executes is independent of the contents of the list. So best case and worst case are the same - and any list of size n would be a correct answer. E.g. "a list of all zeroes" or "a list of the integers from 1 to n"4
u/alpicola Oct 14 '26
It was probably a mistake for you to start talking Big-O notation right off the bat. So many people in this thread seem overly fixated on Big-O and are missing what the question has actually asked. This isn't a question about time complexity, it's a question about identifying "pathological" cases.
This function has a couple of trivial cases:
You will get the best performance if the array is empty (n == 0). In this case, the if statement (line 4) will will read true and the function will immediately return a constant (line 5).
You will get worse performance if the array has a single element (n == 1). In this case, the if statement (line 4) will read false and the function will:
This function also has specific performance characteristics for sorted arrays:
If the array is sorted in ascending order, line 11 will always read true and line 12 will always happen. This is the worst case because it executes every line of the function (except line 5) the maximum possible number of times.
If the array is sorted in descending order, line 11 will always read false and line 12 will never happen. This is the best non-trivial case because it uses the entire function except for line 12.
Unsorted arrays will fall somewhere in between the ascending and descending order scenarios because line 12 will be executed some of the time but not all of the time. This is the average or expected case.
4
u/Newbane2_ Oct 15 '26
I don't really get the question, it's just finding the largest double in the array in O(n) time. I guess a sorted array in descending order would be best case (fewest number of assignments) and ascending order would be worst case (most number of assignments) although they would still both be O(n) since you need to iteration through every element in the array and do a comparison for every element.
6
u/First_Funny_9402 Oct 14 '26
So #1 figure out what this is doing, by the end of the algorithm l will contain the max value of the input array. Now for best/worst case see how many operations are done given an input. No matter what, a comparison is made between every value of the array and the current value of l. What changes based on the input is if l is updated. So a best case would be one where the first element is the max element of the input array, because l gets set to a[0] and then there is no a[i] greater than that value to cause l to be updated. The worst case is an array that is sorted in ascending order, where a[i+1]>a[i] for all i, causing l to be updated after the comparison at every step.
2
u/lostshelby Oct 14 '26
So you're being asked to describe the array, of size n, which produces the best and worst case. Now, if n was 0 then yes, you get a constant time, however that is not the question. To describe the array (of size n, not size 0) it needs to be something where it iterates over all n elements but doesn't really do much. This is a find max algorithm, which sets max as the first element then check all other n-1 elements. Ideally, the first element IS the max value and then it never needs to update the variable after that point. Consider the worst case scenario, the array values are in ascending order, meaning the max updates every time. Strictly speaking though they are both just linear.
2
u/Comp_Sci_Doc Oct 14 '26
O(1) means that the algorithm takes a constant amount of time to execute, regardless of the size of the input. You can't do that here, because if the array has any elements in it, you're going to loop over all of them. What you can do is select an input that will minimize/maximize the number of operations required for a given array size.
2
u/golfstreamer Oct 14 '26
The function goes through the same number of steps for all arrays of length n so the best case and worst case should be the same
2
u/Responsible-Bar7165 Oct 15 '26 edited Oct 15 '26
which processor architecture / version ? if that's not specified then there's no way to answer the question.
on modern arm / x64 it won't make a difference what the values are, the branch predictor and out-of-order dispatch will eliminate all measurable differences, especially if the JIT can vectorize that loop.
3
u/psicodelico6 Oct 14 '26
Best case: O(n)
1
u/SmokeMuch7356 28d ago
O(1) means constant time - it takes the same amount of time regardless of the input size.
This particular algorithm depends on the size of the array, so it's O(N).
1
u/enchantedtotem Oct 14 '26
if n is sufficient large it’s about O(n) (1 assign + (n-1) compare) for monotonic increasing array, and roughly O(2n) (n assigns and (n-1) compares) for monotonic decreasing array.
1
u/Heapifying Oct 14 '26
O-notation is a set of functions. When you say O(1), you actually mean O(x->1), where -> represents a mapping. For example O(n²) is actually O(n->n²), or well if you want, f(n)=n², then you rewrite it as O(f).
You are working with functions here. You usually declare T(n) = "the amount of primitive steps when the array has length n". Usually, you use comparisons (<) as the primitive you are counting. In this case T(0)=1, T(1)=1.
The question is then, is there a family of arrays of any length, such that T \in O(1) for any array in that family?
1
u/Rararror Oct 14 '26
arr[x] = y
0 <= x <= n
For every n:
y <=1 is best case
y >1 is worst case
Complexity is always O(n)
1
u/WafflePeak Oct 14 '26
We always assume n is going to infinity for this sort of analysis, the best case is N
It could really only be constant in this case if line 12 was a break or something that would terminate the loop.
Also be careful about describing best case with O notation, it’s generally better to use Theta notation for it.
1
u/XNo_Notes Oct 14 '26
You need to give an array. Like what string of numbers would make this function work the shortest amount of time. So best case would be an empty array, worst case would be an array at size max full of 2s.
1
u/Neither_Berry_100 Oct 15 '26
Looks like it returns the max or zero if the array is empty. Checks every index exactly once. O(n). Always. No best or worst case. Technically it has some fixed overhead. So if the array is empty you have cost / 0 elements. = infinite cost per elements lol. But just O(n).
1
u/AmbitiousSet5 Oct 15 '26
Big O is asymptotic analysis, as n approaches infinity. Best case doesnt mean just choosing a specific n. Its always as n goes to infinity.
1
u/3inthecorner Oct 15 '26
If the first element is the largest, you avoid all the assignments to
land if it's in ascending order, you do all of them, but the actual worst case is when the branch predictor gets confused. How would you craft an array that each element has a 50% chance of being the largest so far?1
u/0xt0bi03 Oct 15 '26
best case is always o(n) actually, it will go through the array no matter what.
1
u/amir650 Oct 16 '26
You only return after having traversed the entire array of N elements …
1
u/dnabre Oct 16 '26
Keep in mind that in general just because it asks for 'best case' and 'worst case' doesn't mean they are different. To what degree those being the same are a "trick question" is up for debate.
If you consider that you were initially thinking O(1) for array size 0 or 1, the question may be focusing on that incorrect understanding.
1
u/InTheHiggsField Oct 16 '26
Best case is the situation where arr[0] is the greatest value in the list. Because then the conditional on line 11 never resolves to true and thus we never do the assignment operation. The worst case is the situation where the array is in ascending order. Then on every element 11 will resolve to true and the assignment operation will occur.
1
u/Thick_Secretary_1528 Oct 17 '26
It is O(n) - linear. It needs to traverse across all values still.
1
u/goos_ Oct 17 '26
You have the right idea, only thing is the question is asking "array of size n" so they wanted an example of arbitrary n, not just n = 0 or n = 1.
1
u/j-joshua Oct 17 '26
Best case what?
If you're looking for big O notation... The function is O(n) for any input.
1
u/Agus_Merino Oct 18 '26
No tiene mucho sentido la pregunta. El algoritmo no tiene una condición de corte específica para una situación particular. El arreglo tiene que ser recorrido n veces bajo cualquier ejecución, no importa si está ordenado de entrada o completamente desordenado.
Alguien podría decir "bueno pero el costo de la operación de ejecutar la asignación (línea 12), bajo ciertas entradas, no se ejecuta". Si, es verdad, pero una asignación es O(1), ejecutarla o no es tan insignificante que se termina diluyendo en el total. Esto puede verse en cuanto tenemos un algoritmo que hace múltiples operaciones de diferentes complejidades y el cálculo de costo queda en algo como, por ejemplo: n + n^2. Este algoritmo inevitablemente es n^2 ya que la operación de orden n termina siendo "absorbida" por la de orden mayor.
1
u/plintervals Oct 18 '26
First of all, whoever wrote this question and name the variable l is Satan.
It's not asking you to change the size of the array. It's asking, given a fixed size n array, come up with an array that gives the best case performance, and an array that gives the worst case performance.
1
u/misingnoglic Oct 18 '26
That would be wrong, or at least misleading. If it was a function to search an array for a value, the best case would be that you find it immediately and return. But in this function you are always looking at every element. Big O is about how runtime grows in proportion to the input size, so the fact that this function returns immediately for an empty array doesn't do anything for you.
1
u/iam-samzz Oct 18 '26
It's completely based on input size. I think ur function returns the max value in the array.
So worst and best case will be O(N) in ur program.
0
u/MyOthrUsrnmIsABook Oct 15 '26
A lot of people are saying the worst case is if the list is sorted in ascending order, since that will cause l to be set the most times. I would argue a jagged ascending array where every other value is larger than any preceding value could be worse, since it would cause branch mispredictions more of the time than a sorted array.
-1
u/WittyStick Oct 14 '26
O(*)is worst-case complexity. The complexity of this function is O(n).The question is asking what specific inputs would complete it constant time versus linear time - in that regard, input 0 will complete in constant time, but any other in linear time.
-9
u/MrKarat2697 Oct 14 '26
an empty array would simply return 0 and complete in O(1), you are right
-2
u/Alex_1503 Oct 14 '26
It says to describe AN input array for the best and worst case, so I think the empty array for "best case" of size 0, idk. The big O is O(n), but best input array is the empty one, right?