Time Complexity
Why not O(2n)?
- Big-O notation gives an approximation of time complexity. - Use general "complexity type", not exact equations. - Ignore leading constants. 2n would be n - Complexity is determined by the highest order function. n+2 would just be n.
Types of Notations
1. Constant : O(1) 2. Logarithmic : O(log n) 3. Linear : O(n) 4. Quadratic : O(n^2) 5. Exponential : O(c^n)
Constant
O(1) - Run-time does not increase with additional inputs. ** very important concept for multiple executions. (Execution stays the same). - Compare first & last numbers Examples: - Array look up - Hash Table Insertion - Queue - Stack - Set. - Tree. addChild - LinkedList. addToTail, removeHead - Graph. addNode, contains, hasEdge, removeEdge Additional: 1. Accessing Array Index (int a = ARR[5];) 2. Inserting a node in Linked List 3. Pushing and Popping on Stack 4. Insertion and Removal from Queue 5. Finding out the parent or left/right child of a node in a tree stored in Array 6. Jumping to Next/Previous element in Doubly Linked List
Exponential
O(c^n) Example: Guessing an N-character Long password.
Logarithmic
O(log n) - Execution time increases, but at a decreasing rate. - Find largest & smallest numbers Examples: Binary search. 1. Binary Search 2. Finding largest/smallest number in a binary search tree 3. Certain Divide and Conquer Algorithms based on Linear functionality 4. Calculating Fibonacci Numbers - Best Method
Linear
O(n) Example: Finding the index of an element in an array. (for-loops) - LinkedList. contains, BST. depthFirstLog, Tree. contains More: 1. Traversing an array 2. Traversing a linked list 3. Linear Search 4. Deletion of a specific element in a Linked List (Not sorted) 5. Comparing two strings 6. Checking for Palindrome 7. Counting/Bucket Sort
Quadratic
O(n^2) - Compare all numbers Example: Constant time operation inside two nested for-loops. 1. Bubble Sort 2. Insertion Sort 3. Selection Sort 4. Traversing a simple 2D array