A large o notation cheat expanse is simply a compact reference for comparing really an algorithm’s moving clip and representation usage turn arsenic input size increases. It matters because a solution that useful for 1,000 UPI transactions whitethorn neglect astatine 10 crore records; aft reading, you tin choose, compare, and warrant algorithms nether existent constraints.
Big-O sits astatine the centre of information structures, algorithms, database indexing, distributed systems, and capacity engineering. Intermediate and precocious learners usage it to estimate scalability earlier penning code, particularly erstwhile accumulation traffic, representation limits, aliases question and reply constraints make brute unit unacceptable.
You will beryllium capable to publication a clip complexity graph, place clip and abstraction complexity from code, revise modular algorithm complexities, and reply question and reply questions pinch precise reasoning alternatively of memorised labels.
Core Concepts
Big-O notation describes asymptotic growth, not nonstop runtime successful milliseconds. To usage this cheat expanse well, abstracted 3 ideas: the mathematical bound, the algorithmic cognition being counted, and the input model. For example, scanning Aadhaar verification logs is linear successful the number of logs, while looking up a costs ID successful a well-sized hash array is expected changeless time.
1.Asymptotic Notation
Big-O, Omega, Theta, little-o, and little-omega are not interchangeable. Big-O gives an precocious bound, Omega gives a little bound, and Theta gives a tight bound. Little-o and little-omega are stricter comparisons utilized successful proofs, particularly erstwhile showing that 1 maturation complaint is decidedly smaller aliases larger than another.
A acquainted illustration is an IRCTC train hunt page. If the strategy scans each train way to find matches, the cognition is O(n). If it uses a sorted scale and binary search, the lookup tin beryllium O(log n). In a banking fraud-detection pipeline, a nested comparison of each transaction against each different transaction is O(n²), while grouping by relationship ID first tin trim repeated work.
Interviewers usually expect the simplest valid asymptotic reply aft dropping constants and lower-order terms. If codification performs 3n + 20 primitive operations, the complexity is O(n), not O(3n) aliases O(n + 20). If codification performs n² + n log n, the ascendant word is O(n²).
For GATE and interviews, the modular mobility is: if T(n) = 4n² + 30n + 100, what is the asymptotic complexity? The modular reply is Theta(n²), because n² is some the precocious and little ascendant maturation term.Code Example
2.Complexity Classes
The astir useful clip complexity cheat expanse starts pinch maturation classes. O(1) is constant, O(log n) is logarithmic, O(n) is linear, O(n log n) is linearithmic, O(n²) and O(n³) are polynomial, and O(2ⁿ) aliases O(n!) are exponential aliases factorial. The jump from O(n log n) to O(n²) is often the quality betwixt passing and timing out.
For a acquainted Indian example, checking whether a PAN number exists successful a hash group is expected O(1), while searching an unsorted database of PAN records is O(n). In healthcare analytics, sorting diligent laboratory reports by timestamp is usually O(n log n), but comparing each diligent pinch each different diligent for similarity becomes O(n²).
A clip complexity chart land input size connected the x-axis and cognition count connected the y-axis. O(log n) grows slowly, O(n) grows steadily, O(n²) bends upward sharply, and O(2ⁿ) becomes unusable very quickly. Such graphs thief explicate why a technically correct brute-force solution tin still beryllium impractical.
| O(1) | Constant | Array scale access, stack push, hash lookup mean case | Work does not turn pinch input size |
| O(log log n) | Double logarithmic | Some integer hunt structures and specialised algorithms | Extremely slow growth, little communal successful interviews |
| O(log n) | Logarithmic | Binary search, balanced BST lookup, heap tallness operations | Input is many times halved aliases reduced by a factor |
| O(sqrt n) | Square-root | Trial section up to quadrate root, artifact decomposition query blocks | Often appears successful number mentation and decomposition |
| O(n) | Linear | Array scan, BFS complete vertices only, counting frequency | Each point is processed a changeless number of times |
| O(n log n) | Linearithmic | Merge sort, heap sort, mean quicksort, businesslike comparison sorting | Typical champion applicable bound for wide comparison sorting |
| O(n²) | Quadratic | Bubble sort, action sort, insertion benignant worst case, brace comparison | Nested loops complete the aforesaid input |
| O(n³) | Cubic | Floyd-Warshall, naive matrix multiplication | Often acceptable only for mini n |
| O(2ⁿ) | Exponential | Subset generation, naive Fibonacci recursion | Each other point tin double the work |
| O(cⁿ) | General exponential | Many brute-force hunt and branching algorithms | Growth depends connected branching facet c |
| O(n!) | Factorial | Permutation generation, brute-force travelling salesperson | All imaginable orderings are explored |
| O(nⁿ) | Super-exponential style growth | Naive duty of n choices to n positions | Usually infeasible beyond mini inputs |
Code Example
3.Analysis Rules
Complexity study follows a fewer repeatable rules. Sequential blocks add, nested loops multiply, independent input sizes must beryllium named separately, and recursive algorithms usually require a recurrence. A loop from 1 to n is O(n); a loop that doubles the antagonistic each clip is O(log n); 2 nested n-sized loops are O(n²).
For a acquainted example, validating each items successful 1 Zomato cart is O(n), but checking each point against each disposable coupon tin go O(nm), wherever n is items and m is coupons. In SaaS analytics, processing users and events separately is O(u + e), while joining each personification pinch each arena naively is O(ue).
Amortised complexity is different modular question and reply topic. Dynamic arrays whitethorn occasionally resize successful O(n), but a agelong series of appends is O(1) amortised per append. Hash tables besides trust connected amortised reasoning erstwhile resizing and rehashing are dispersed crossed galore operations.
A communal correction is penning O(n²) for immoderate codification pinch 2 loops. If the loops are sequential, the complexity is O(n + n), which simplifies to O(n). Multiplication applies erstwhile 1 loop runs wrong the other.Code Example
4.Searching Algorithms
Searching complexity depends chiefly connected whether the information is ordered and whether nonstop addressing is available. Linear hunt is O(n) because it whitethorn inspect each element. Binary hunt is O(log n), but only erstwhile the information is sorted and random entree is efficient. Hash lookup is expected O(1), but worst-case O(n) if galore keys collide.
A acquainted illustration is uncovering 1 mobile number successful an unsorted interaction export, which is linear search. Searching a sorted database of railway position codes tin usage binary search. In banking systems, retrieving a transaction by ID from a hash scale is expected changeless time, while scope queries specified arsenic transactions betwixt 2 timestamps are amended served by balanced trees aliases database indexes.
| Linear search | O(1) | O(n) | O(n) | O(1) | No ordering required |
| Binary search | O(1) | O(log n) | O(log n) | O(1) iterative, O(log n) recursive | Sorted random-access data |
| Jump search | O(1) | O(sqrt n) | O(sqrt n) | O(1) | Sorted random-access data |
| Interpolation search | O(1) | O(log log n) | O(n) | O(1) | Sorted and near-uniform distribution |
| Exponential search | O(1) | O(log i) | O(log i) | O(1) | Sorted unbounded aliases ample array, target astatine scale i |
| Hash array lookup | O(1) | O(1) expected | O(n) | O(n) | Good hashing and load factor |
Code Example
5.Sorting Algorithms
Sorting is 1 of the astir tested areas because respective algorithms lick the aforesaid problem pinch different trade-offs. Bubble, selection, and insertion benignant are elemental but usually O(n²). Merge benignant and heap benignant guarantee O(n log n). Quicksort is O(n log n) connected mean but O(n²) successful the worst lawsuit without bully pivot handling.
Non-comparison sorts person different constraints. Counting benignant is O(n + k), wherever k is the cardinal range. Radix benignant is O(d(n + b)), wherever d is the number of digits and b is the guidelines aliases bucket count. Bucket benignant tin beryllium O(n + k) connected mean erstwhile information is uniformly distributed, but it tin degrade if buckets go uneven.
A acquainted illustration is sorting UPI transactions by magnitude for a monthly statement. For arbitrary amounts, merge benignant aliases quicksort-style sorting is reasonable. In an ed-tech level sorting exam scores from 0 to 100, counting benignant tin beryllium fantabulous because the scope is mini and known.
| Bubble sort | O(n) pinch early stop | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No by default |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quicksort | O(n log n) | O(n log n) | O(n²) | O(log n) mean stack | No by default |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes if implemented carefully |
| Radix sort | O(d(n + b)) | O(d(n + b)) | O(d(n + b)) | O(n + b) | Yes pinch unchangeable soul sort |
| Bucket sort | O(n + k) | O(n + k) | O(n²) | O(n + k) | Depends connected bucket sorting |
| Timsort | O(n) | O(n log n) | O(n log n) | O(n) | Yes |
Code Example
6.Data Structures
Data building complexity is astir cognition cost: access, search, insert, delete, peek, enqueue, dequeue, and resize. Arrays supply O(1) scale entree but costly mediate insertion. Linked lists support O(1) insertion if the node reference is known, but O(n) search. Hash tables supply expected O(1) lookup, insert, and delete, pinch O(n) worst lawsuit nether collisions.
A acquainted illustration is storing caller OTP attempts successful a stack-like building wherever push and popular are O(1). In e-commerce inventory systems, merchandise ID to banal count is usually a hash representation because expected lookup is O(1). For ordered leaderboard queries successful gaming aliases ed-tech, a balanced character is amended than a plain hash representation because it supports sorted traversal.
| Static array | O(1) | O(n) | O(n) | O(n) | O(n) |
| Dynamic array | O(1) | O(n) | O(1) amortised append, O(n) middle | O(n) | O(n) |
| Singly linked list | O(n) | O(n) | O(1) astatine caput aliases known node | O(1) pinch erstwhile reference, different O(n) | O(n) |
| Doubly linked list | O(n) | O(n) | O(1) astatine known node | O(1) astatine known node | O(n) |
| Stack | O(n) | O(n) | O(1) push | O(1) pop | O(n) |
| Queue | O(n) | O(n) | O(1) enqueue | O(1) dequeue | O(n) |
| Deque | O(n) | O(n) | O(1) astatine some ends | O(1) astatine some ends | O(n) |
| Hash table | Not scale based | O(1) expected, O(n) worst | O(1) expected, O(n) worst | O(1) expected, O(n) worst | O(n) |
Code Example
7.Trees And Heaps
Tree complexity depends connected height. A balanced binary hunt character has tallness O(log n), truthful search, insert, and delete are O(log n). A skewed BST tin degrade to O(n). Heaps support accelerated minimum aliases maximum entree successful O(1), insertion successful O(log n), and extract-min aliases extract-max successful O(log n).
A acquainted illustration is autocomplete suggestions stored successful a trie, wherever lookup depends connected connection magnitude alternatively than full number of words. In nutrient transportation dispatch, a privilege queue tin delegate the nearest aliases highest-priority bid by many times extracting the champion campaigner successful O(log n). In record systems and compilers, trees are besides utilized for hierarchical and syntax representations.
| Unbalanced BST | O(h), worst O(n) | O(h), worst O(n) | O(h), worst O(n) | O(h) | O(n) |
| AVL tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Red-black tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Binary heap | O(n) | O(log n) | O(log n) extract root | O(1) guidelines access | O(n) |
| Trie | O(L) | O(L) | O(L) | Not applicable | O(total characters) |
| B-tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
Code Example
8.Graph Algorithms
Graph complexity is usually expressed pinch V for vertices and E for edges. BFS and DFS are O(V + E) pinch adjacency lists because each vertex and separator is processed a bounded number of times. With an adjacency matrix, scanning neighbours tin costs O(V²), moreover if the chart has fewer edges.
Shortest way and spanning character algorithms dangle connected information structures. Dijkstra pinch a binary heap is commonly O((V + E) log V). Bellman-Ford is O(VE) and handles antagonistic separator weights. Floyd-Warshall is O(V³) and is useful for all-pairs shortest paths connected smaller dense graphs. Kruskal is O(E log E), while Prim is often O(E log V) pinch a heap.
A acquainted illustration is metro way readying wherever stations are vertices and tracks are edges. In logistics, warehouses, transportation hubs, and roadworthy segments shape weighted graphs for way optimisation. In societal networks, friend recommendations often usage chart traversal and neighbourhood description .
| BFS | O(V + E) | O(V) | Shortest way successful unweighted graphs, level traversal |
| DFS | O(V + E) | O(V) | Connectivity, rhythm detection, topological traversal |
| Topological sort | O(V + E) | O(V) | Dependency ordering successful DAGs |
| Dijkstra pinch binary heap | O((V + E) log V) | O(V + E) | Non-negative weighted shortest paths |
| Bellman-Ford | O(VE) | O(V) | Shortest paths pinch antagonistic edges |
| Floyd-Warshall | O(V³) | O(V²) | All-pairs shortest paths |
| Kruskal MST | O(E log E) | O(V) | Minimum spanning character utilizing sorting and DSU |
| Prim MST pinch heap | O(E log V) | O(V + E) | Minimum spanning character from a commencement vertex |
| Union-Find operations | Almost O(1), inverse Ackermann amortised | O(V) | Connectivity and Kruskal MST |
Code Example
9.Dynamic Programming
Dynamic programming complexity is usually the number of states multiplied by the modulation costs per state. Memoisation stores solved subproblems successful a cache, while tabulation fills a array iteratively. DP often converts exponential recursion into polynomial clip by avoiding repeated work.
A acquainted illustration is calculating the number of ways to climb steps, wherever naive recursion repeats the aforesaid calls exponentially. A fintech illustration is computing optimal repayment schedules nether constraints, wherever each authorities whitethorn correspond month, balance, and determination choice. In proposal systems, series alignment and edit region usage DP complete 2 dimensions.
Common DP complexities see O(n) for one-dimensional recurrence, O(nW) for 0/1 knapsack pinch capacity W, O(n²) for longest expanding subsequence DP, O(nm) for edit distance, and O(n³) for matrix concatenation multiplication. Optimised variants whitethorn trim abstraction from O(nm) to O(min(n, m)) erstwhile only the erstwhile statement is needed.
| Fibonacci pinch memoisation | O(n) | O(n) | n |
| Climbing stairs | O(n) | O(1) optimised | current step |
| 0/1 knapsack | O(nW) | O(nW) aliases O(W) | item scale and capacity |
| Edit distance | O(nm) | O(nm) aliases O(min(n, m)) | prefix lengths |
| Longest communal subsequence | O(nm) | O(nm) | two prefix lengths |
| Longest expanding subsequence DP | O(n²) | O(n) | best ending astatine index |
| LIS pinch binary search | O(n log n) | O(n) | minimum tail values |
| Matrix concatenation multiplication | O(n³) | O(n²) | interval boundaries |
Code Example
10.Backtracking And Recursion
Backtracking explores choices, undoing a prime erstwhile it cannot lead to a valid solution. Its complexity is often exponential aliases factorial because the algorithm walks a hunt tree. The nonstop bound depends connected the number of choices astatine each level and the extent of the determination tree.
A acquainted illustration is generating each imaginable PIN patterns nether constraints; each other digit increases the hunt space. In recreation planning, brute-forcing each metropolis bid for a mini travelling salesperson version is O(n!), because it checks permutations. In scheduling systems, assigning slots to sessions tin go exponential erstwhile each convention has aggregate valid rooms and times.
Recursion besides adds abstraction complexity done the telephone stack. A depth-n recursion uses O(n) stack abstraction moreover if it stores nary other array. Backtracking whitethorn additionally shop the existent path, visited flags, and consequence list; if each solutions are stored, output size tin predominate memory.
Do not disregard output size. Generating each subsets takes O(n2ⁿ) clip if each subset is copied, and O(n2ⁿ) abstraction if each subsets are stored.Code Example
11.String Algorithms
String complexity depends connected length, alphabet size, and whether repeated comparisons are avoided. Naive substring hunt tin beryllium O(nm), wherever n is matter magnitude and m is shape length. KMP preprocesses the shape and searches successful O(n + m). Rabin-Karp is expected O(n + m), but hash collisions tin origin O(nm) worst case.
A acquainted illustration is searching for a train number wrong a agelong SMS inbox export. Naive hunt whitethorn beryllium good for mini text, but indexing aliases KMP-style scanning matters astatine scale. In cybersecurity, scanning logs for onslaught signatures benefits from businesslike drawstring matching because the aforesaid patterns are checked crossed millions of lines.
| Naive shape search | O(nm) | O(1) | Small matter aliases elemental implementation |
| KMP | O(n + m) | O(m) | Deterministic substring search |
| Rabin-Karp | O(n + m) expected, O(nm) worst | O(1) | Multiple shape matching pinch hashing |
| Z algorithm | O(n + m) | O(n + m) | Pattern matching and prefix analysis |
| Trie prefix search | O(L) | O(total characters) | Autocomplete and dictionary prefixes |
| Suffix array construction | O(n log n) communal implementations | O(n) | Fast substring queries aft preprocessing |
Code Example
12.Number Theory
Number mentation complexities often dangle connected the worth of n, not conscionable the number of input items. Checking primality by trying each divisor up to n is O(n), but trying only up to quadrate guidelines is O(sqrt n). Euclid’s GCD algorithm is O(log min(a, b)) because remainders shrink quickly.
A acquainted illustration is validating elemental divisibility rules for invoice numbers, wherever modulus operations are constant-time for emblematic machine-sized integers. In cryptography and information systems, modular exponentiation matters because naive repeated multiplication is excessively slow; accelerated exponentiation runs successful O(log exponent) multiplications.
| Euclidean GCD | O(log min(a, b)) | O(1) iterative | Fractions, modular arithmetic |
| Trial section primality | O(sqrt n) | O(1) | Basic primality check |
| Sieve of Eratosthenes | O(n log log n) | O(n) | All primes up to n |
| Fast exponentiation | O(log exponent) | O(1) iterative | Modular powerfulness calculations |
Code Example
13.Space Complexity
Space complexity measures really representation grows pinch input size. It includes auxiliary information structures, recursion stack, memo tables, copied arrays, queues, heaps, and output retention erstwhile the output is portion of the algorithm’s representation footprint. Many learners attraction only connected clip and miss stack aliases array memory.
A acquainted illustration is storing each monthly UPI transactions successful a database earlier processing, which costs O(n) space. Streaming 1 transaction astatine a clip and maintaining only a moving full costs O(1) auxiliary space. In healthcare image processing, copying each image during translator whitethorn double representation use, while in-place updates trim auxiliary abstraction erstwhile safe.
Recursive DFS uses O(h) stack abstraction connected a character of tallness h, and O(V) successful the worst lawsuit connected a chart if recursion follows a agelong path. Merge benignant uses O(n) auxiliary abstraction because merging requires other arrays. Heap benignant is O(1) auxiliary abstraction erstwhile performed successful place.
Recursive codification is not automatically O(1) space. Even if nary database is created, each progressive usability telephone consumes stack memory.Code Example
A complete complexity reply should specify input variables, clip case, abstraction usage, and assumptions. Example: BFS connected an adjacency database takes O(V + E) clip and O(V) auxiliary space.Algorithm Cheat Sheets
The tables beneath cod the modular complexities astir often utilized successful exams, codification reviews, and interviews. Treat them arsenic a revision sheet, but still deduce the reply from loops, recursion, states, aliases chart practice erstwhile asked to explain.
Arrays And Strings
| Array scale access | O(1) | O(1) |
| Array hunt unsorted | O(n) | O(1) |
| Insert astatine extremity move array | O(1) amortised | O(1) extra, O(n) during resize |
| Insert aliases delete astatine middle | O(n) | O(1) |
| Two-pointer scan | O(n) | O(1) |
| Sliding window | O(n) | O(1) to O(k) |
| Prefix sum build | O(n) | O(n) |
| Prefix sum scope query | O(1) | O(n) preprocessing |
Linked Lists
| Access by index | O(n) | O(n) |
| Search | O(n) | O(n) |
| Insert astatine head | O(1) | O(1) |
| Insert aft known node | O(1) | O(1) |
| Delete known node | O(n) if erstwhile node unknown | O(1) |
| Reverse list | O(n) | O(n) |
Stacks And Queues
| Stack | push, pop, peek | O(1) | O(n) |
| Queue | enqueue, dequeue, front | O(1) | O(n) |
| Deque | insert and delete astatine some ends | O(1) | O(n) |
| Monotonic stack | next greater aliases smaller element | O(n) total | O(n) |
| Monotonic queue | sliding model maximum | O(n) total | O(k) |
Hashing And Sets
| Insert key | O(1) | O(n) | O(n) |
| Search key | O(1) | O(n) | O(n) |
| Delete key | O(1) | O(n) | O(n) |
| Rehash resize | O(n) for that resize | O(n) | O(n) |
Graphs Summary
| Adjacency list | O(V + E) | O(degree) unless hashed | O(degree) |
| Adjacency matrix | O(V²) | O(1) | O(V) |
| Edge list | O(E) | O(E) | O(E) |
Learning Path
Use this way to move from recognising Big-O labels to deriving them nether question and reply pressure. The extremity is not memorising each row; it is knowing which cognition causes the growth.
Frequently Asked Questions
What is simply a large o notation cheat sheet?
A large o notation cheat expanse is simply a speedy reference that lists communal algorithm and information building complexities. It helps you comparison approaches by maturation rate, specified arsenic O(n), O(n log n), O(n²), and O(2ⁿ), alternatively than by machine-specific runtime.
What is the quality betwixt clip complexity and abstraction complexity?
Time complexity measures really the number of operations grows pinch input size. Space complexity measures really representation usage grows, including auxiliary structures and recursion stack. A solution tin person bully clip complexity but mediocre abstraction complexity, specified arsenic DP pinch a ample table.
What is the quality betwixt Big-O, Omega, and Theta?
Big-O is an precocious bound, Omega is simply a little bound, and Theta is simply a tight bound. If merge benignant is described arsenic Theta(n log n), it intends its maturation is bounded supra and beneath by n log n up to changeless factors.
How do I cipher Big-O from code?
Count really galore times the main activity runs arsenic input grows. Sequential loops add, nested loops multiply, halving loops are logarithmic, and recursive codification is analysed done a recurrence aliases recursion tree. Drop constants and lower-order position astatine the end.
When should I usage O(n log n) sorting alternatively of O(n²) sorting?
Use O(n log n) sorting for mean aliases ample inputs, accumulation systems, and astir question and reply solutions. O(n²) sorting whitethorn beryllium acceptable for mini arrays, astir sorted information pinch insertion sort, aliases school purposes, but it scales poorly.
Why is binary hunt O(log n)?
Binary hunt halves the remaining hunt abstraction aft each comparison. After k steps, the remaining size is astir n divided by 2ᵏ, truthful the hunt finishes erstwhile k is astir log₂ n.
Is hash array lookup ever O(1)?
No. Hash array lookup is expected O(1) erstwhile hashing distributes keys good and the array maintains a patient load factor. In the worst case, galore keys tin collide and lookup tin degrade to O(n).
What is amortised clip complexity?
Amortised complexity describes the mean costs per cognition complete a sequence, moreover if 1 cognition is occasionally expensive. Dynamic array append is O(1) amortised because uncommon O(n) resizes are dispersed crossed galore inexpensive appends.
What is the astir communal correction successful Big-O analysis?
The astir communal correction is giving a complexity without assumptions. For example, BFS is O(V + E) only erstwhile utilizing an adjacency list; practice matters. Another communal correction is ignoring recursion stack space.
Key Takeaways
The astir important points are concrete: Big-O is an asymptotic maturation bound, Theta is the tight bound, nested loops multiply, recursive calls adhd stack space, and chart complexity must mention V, E, and representation. Sorting, hashing, DP, and chart traversal are the highest-value areas to revise.
For GATE and interviews, expect questions connected binary hunt O(log n), comparison sorting Omega(n log n), BFS and DFS O(V + E), hash array expected O(1) versus worst O(n), merge benignant O(n log n) clip and O(n) space, and DP complexity arsenic states multiplied by modulation cost.
The earthy adjacent measurement is to lick mixed algorithm problems and constitute the clip and abstraction complexity beside each solution earlier coding. Build your ain one-page revision expanse from the tables supra and update it whenever you study a caller pattern.
English (US) ·
Indonesian (ID) ·