Constant Time
Constant Time
πŸ“

Understanding Time Complexity of OLog(N): Math + Intuition

For most binary search problems, we reduce the array size by half at each iteration. To find the time complexity, we can ask how many times we will have to divide our original array of size (n) until we reach 1.

nβˆ—12βˆ—12βˆ—12βˆ—12βˆ—12...=1n * \frac{1}{2}* \frac{1}{2}* \frac{1}{2}* \frac{1}{2}* \frac{1}{2}... = 1nβˆ—21β€‹βˆ—21β€‹βˆ—21β€‹βˆ—21β€‹βˆ—21​...=1

nβˆ—(12)x=1n * (\frac{1}{2})^x = 1nβˆ—(21​)x=1 (x = how many times)

nβˆ—(1x2x)=1n * (\frac{1^x}{2^x}) = 1nβˆ—(2x1x​)=1

nβˆ—(12x)=1n * (\frac{1}{2^x}) = 1nβˆ—(2x1​)=1

(n2x)=1(\frac{n}{2^x}) = 1(2xn​)=1

n=2xn = 2^xn=2x

How to Separate x out of the exponent. Logarithms? Take log base 2 on both sides

log⁑2n=log⁑22x\log_{2} n = \log_{2} 2^xlog2​n=log2​2x

What power must we raise 2 to get 2^x , that is just x

log⁑2n=x\log_{2} n = xlog2​n=x

We need to half the array log n times to get to 1. So that’s how many times we need to make iterations on an array of size n.

Time Complexity: O(log(n))

πŸ’‘
Reference(Time complexity)
πŸ’‘
Reference(Logarithms)

Logo
YouTubeDiscord