Learn about Big O notation and how to analyze the complexity of algorithms.
Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. In computer science, it's used to classify algorithms according to how their run time or space requirements grow as the input size grows.
Analyzing time complexity involves determining how the runtime of an algorithm grows as the input size increases.
// Accessing an element in an array by index int value = array[5]; // O(1) // Checking if a number is even boolean isEven = (number % 2 == 0); // O(1)
// Iterating through an array once for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } // O(n)
// Nested loops for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { System.out.println(array[i] + array[j]); } } // O(n²)
Space complexity measures the amount of memory an algorithm needs as input size grows.
// Using a fixed number of variables int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } // O(1) space complexity
// Creating a new array of the same size as input int[] duplicate = new int[array.length]; for (int i = 0; i < array.length; i++) { duplicate[i] = array[i]; } // O(n) space complexity
When comparing algorithms that solve the same problem, we analyze both time and space complexity to determine which is more efficient.
For example, when searching for an element:
When choosing between algorithms, consider: