B2.4.1Big O Notation and Algorithm Efficiency
0/9
B2.4 Programming algorithmsB2.4.1

Big O Notation and Algorithm Efficiency

Describe the efficiency of specific algorithms by calculating their Big O notation to analyse their scalability

SL + HL≈ 60 minCommand term: DescribeFree lesson

In this lesson

  • Explaining time and space complexity
  • Calculating the Big O notation of an algorithm from its loops
  • Comparing how the common complexity classes scale as the input grows
  • Choosing an algorithm based on scalability and efficiency requirements

LearnMeasuring efficiency

    0 of 5

    LearnCommon complexity classes

    From the most to the least efficient.

    Big ONameTypical example
    O(1)ConstantAccessing an array element by its index; push and pop on a stack.
    O(log n)LogarithmicBinary search: the data still to be searched halves at every step.
    O(n)LinearLinear search; any single loop that visits every item once.
    O(n log n)LinearithmicEfficient sorts such as merge sort, and quicksort in the average case.
    O(n²)QuadraticBubble sort and selection sort; two nested loops that each run up to n times.
    O(2ⁿ)ExponentialTrying every subset of n items; the naive recursive Fibonacci function.
    O(n!)FactorialTrying every possible order of n items, e.g. every route through n towns.

    LabHow the classes grow

    Move the slider to change n and watch how many operations each class needs.

    Big OOperations for this nTime at 10⁹ operations per second
    O(1) constant11 ns
    O(log n) logarithmic55 ns
    O(n) linear1616 ns
    O(n log n) linearithmic8080 ns
    O(n²) quadratic256256 ns
    O(2ⁿ) exponential65,53665.5 µs
    O(n!) factorial2.09 × 10¹³5.81 hours

    The bars use a logarithmic scale: the bar grows by the same length each time the number of operations is multiplied by ten. The O(log n) row shows the most comparisons a binary search of n items needs.

    Predict: when n doubles, the number of operations…
    O(n)

    O(n²)

    O(log n)

    LearnCalculating Big O from code

      0 of 4

      CodeO(1): no loop

      def percent(x, y):
      return x / y * 100
      print(percent(18, 24))
      Output
      75.0

      A division and a multiplication, whatever the values: the work never changes.

      CodeO(n): one loop

      def findMax(values):
      highest = values[0]
      for i in range(1, len(values)):
      if values[i] > highest:
      highest = values[i]
      return highest
      temps = [14, 19, 11, 23, 17]
      print(findMax(temps))
      Output
      23

      The loop compares each remaining element once, so the number of comparisons is n − 1: it grows in line with n.

      CodeO(n²): nested loops

      def hasDuplicate(names):
      for i in range(len(names)):
      for j in range(len(names)):
      if i != j and names[i] == names[j]:
      return True
      return False
      team = ["Ola", "Pim", "Rae", "Pim"]
      print(hasDuplicate(team))
      Output
      True

      In the worst case (no duplicates) the inner loop runs n times for each of the n passes of the outer loop: n × n comparisons.

      CodeO(log n): halving

      n = 1000
      steps = 0
      while n > 1:
      n = n // 2
      steps = steps + 1
      print(steps)
      Output
      9

      Halving 1000 repeatedly reaches 1 after 9 steps (whole-number division). Doubling n to 2000 would add only one more step.

      CheckWhich class?

      Classify the worst-case time complexity of each task for n items.

      1. Read the first item of an array
      2. Add up every number in a list
      3. Compare every student’s mark with every other student’s mark
      4. Guess a number from 1 to n, always guessing the middle of the numbers still possible and being told “higher” or “lower”
      5. Print a grid of n rows and n columns
      6. Pop the top item off a stack
      7. Find the cheapest price in an unsorted list
      8. Find a word in a sorted dictionary by opening it at the middle of the remaining pages each time

      LearnSpace complexity

        0 of 3

        CheckQuick check

        A linear (O(n)) search takes 3 ms on a list of 5,000 items. Roughly how long would it take on 20,000 items?

        LearnChoosing an algorithm

          0 of 3

          ExamWorked exam answer

          Determine the Big O time complexity of weeklyReport, where n is the number of values in sales. Justify your answer.

          [3]
          def weeklyReport(sales):
          for s in sales:
          for day in range(1, 8):
          print("Day", str(day) + ":", s)
          weeklyReport([5])
            Try writing your own answer first.

            ReviewMistakes examiners see

            Misconception

            Saying that nested loops are always O(n²): check how many times each loop runs.

            Misconception

            Giving the best case: Big O describes the worst case unless the question says otherwise.

            Misconception

            Keeping constants, e.g. writing O(2n) or O(n² + n), instead of O(n) and O(n²).

            Exam tip

            In a Describe or Explain answer about efficiency, say what n is and how the number of operations changes when n grows.

            Exam practiceExam-style questions

            4 questions · 11 marks. Answer each one first, then mark it yourself against the markscheme. Your answers are saved in this browser only.

            Scenario

            A music app stores the titles of the songs in a user’s library in an array. Each song also has a tempo in beats per minute (bpm).

            (a)State · AO1[3]

            State the Big O time complexity of songAt and of countLonger, and the extra space complexity of countLonger, where n is the number of songs.

            titles = ["Halo", "Rush", "Mono", "Glow"]
            def songAt(position):
            return titles[position]
            def countLonger(length):
            count = 0
            for t in titles:
            if len(t) > length:
            count = count + 1
            return count
            print(songAt(2), countLonger(3))
            (b)Explain · AO3[3]

            similarPairs counts the pairs of songs whose tempos differ by 2 bpm or less, so that the app can suggest songs to play one after the other. Explain why its time complexity is O(n²), even though the inner loop does not always run n times.

            def similarPairs(bpm):
            pairs = 0
            for i in range(len(bpm)):
            for j in range(i + 1, len(bpm)):
            if abs(bpm[i] - bpm[j]) <= 2:
            pairs = pairs + 1
            return pairs
            print(similarPairs([120, 121, 90, 118]))
            (c)Calculate · AO2[2]

            For a library of 2,000 songs, similarPairs takes 0.5 seconds. Calculate roughly how long it would take for 10,000 songs.

            (d)Explain · AO3[3]

            To sort songs by tempo, the developer can use an O(n²) sort or an O(n log n) sort. Explain why the choice hardly matters for a playlist of 20 songs, but does matter for a streaming service’s catalogue of 2 million songs.

            0 / 11

            0 of 4 questions marked. Mark every question to see your total.

            Exam-style questions written for Praxis IB in the format of the 2027 specimen papers. They are not IB past-paper questions.