Preparing for technical interviews can be difficult, frustrating, and confusing at times. As I continue my job search I thought I would take some time to share what I’ve learned thus far about calculating time complexity, and Big O notation. This topic wasn’t easy for me to grasp when it was first introduced at Flatiron, but the idea behind Big O is actually fairly simple once you delve into it a little further. Here is a rundown of how it works, and what you need to know to start nailing those tech interview questions!

First off, when people say “Big O” they’re really referring to Big ϴ (“big theta”). This concept looks to evaluate the limiting behavior of a function as it approaches a specific value/infinity. Essentially you’re looking at the worst case scenario when working with Big O or the “upper asymptotic bound.” To calculate time complexity you only need to look at the term with the largest exponent, ignore coefficients/smaller terms, and you can also count the number of nested loops in your function to help determine Big O. Let me give an example using Linear search with a Ruby implementation. In this example I’m trying to find a specific target number — 23 in a shuffled array of 60 numbers.

array = [*1..60].shuffle

def linear_search(array, target)
  counter = 0

  # iterate through the given array starting 
  # at index 0 and continue until the end

  while counter < array.length 
    if array[counter] == target 
      # exit the loop if the target element is found 
      return "Took: #{counter} iterations to find the target" 
    else 
      counter += 1
    end 
  end 

  return "#{target} could not be found in the array" 
end
linear_search(array, 23)

Running my method linear_search 5 times gave this output when trying to find the target — 23.

=> "Took: 12 iterations to find the target"
=> "Took: 20 iterations to find the target"
=> "Took: 37 iterations to find the target"
=> "Took: 55 iterations to find the target"
=> "Took: 30 iterations to find the target"

Essentially what this output is telling us is that given our function the smallest number of iterations it could take to find the target would be 1, if it was shuffled to index 0 of the array. More importantly the worst case scenario would be 60 iterations if it got shuffled to the end. If our array was 150 numbers/items it would have a worst case scenario of 150 iterations. The Big O notation for Linear search is O(n), where n simply equals the number of elements in the collection.

#time-complexity #big-o-notation #data-structures #algorithms #algorithms

Big O Notation: Calculating Time Complexity
1.25 GEEK