How to find the kth largest element in an unsorted array of length n in O(n)?
How to find the kth largest element in an unsorted array of length n in O(n)?
How to find the kth largest element in an unsorted array of length n in O(n)?
You model the time function to calculate Fib(n) as sum of time to calculate Fib(n-1) plus the time to calculate Fib(n-2) plus the time to add them together (O(1)). This is assuming that repeated evaluations of the same Fib(n) take the same time – i.e. no memoization is used. T(n<=1) = O(1) T(n) = T(n-1) … Read more
I’ll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the Data Structures and Algorithms in Java book. There is no mechanical procedure that can be used to … Read more
What is a plain English explanation of “Big O” notation?
To be honest, if you feel like showing the guys teaching your course that their problem statement probably isn’t what they intended, I would just do it this way: for(int i = 0; i < c; i++) { /*your code here*/} This is in O(c), and since O(c) is a strict subset of O(ck) for … Read more
We have: 1 : if statement 3 : * operator 3 : function statement Totally: 7 So we have: T(n)=t(n-1) + t(n-2) + t(n-3) + 7 T(99)=1 T(98)=1 … T(1)=1 Then to reduce T(n), we have T(n-3)<T(n-2)<T(n-1) therefore: T(n) <= T(n-1)+T(n-1)+T(n-1) + 7 T(n) <= 3T(n-1) + 7 So we can solve T(n) = 3T(n-1) … Read more
Assuming that T(n) doesn’t suddenly become negative at some value of n, we can give a lower bound for the left hand side if we neglect the first term: We define a new function S(n) such that: We can immediately see that it has terms (ignoring off-by-one etc.). Thus if we keep expanding: At this … Read more
Since there is no loop, it is O(1).
Question 1 : O(n) because it increments by constant (1). first loop O(n) second loop also O(n) total O(n) + O(n) = O(n) Question 2 : O(lg n) it’s binary search. it’s O(lg n), because problem halves every time. if the array is size n at first second is n/2 then n/4 ….. 1. n/2^i … Read more
For comparison sorting we consider the number of comparisons, sorting complicated objects this usually dominates. Your outer loop always runs count times, your inner loop always runs on average ~count / 2 times. Every iteration of the inner loop always does one comparison. Hence you get best, worst and average case is count * count … Read more