Big O Notation: Time Complexity, Cheat Sheet & Code Examples

Jul 01, 2026 09:59 PM - 2 hours ago 115

Big O notation is simply a mathematical measurement to picture really an algorithm’s moving clip aliases representation usage grows arsenic input size increases. It matters because a hunt that useful for 100 records whitethorn neglect for 10 crore records. After reading, you tin comparison algorithms earlier penning accumulation code.

Big O sits wrong algorithm analysis, on pinch correctness, separator cases, information structures, and implementation choices. If you are revising algorithm creation basics, the narration betwixt steps, logic, and practice is covered successful Big O Notation: Space and Time Complexity.

You will beryllium capable to place communal clip complexities, simplify Big O expressions, publication a large o cheat expanse correctly, and reply GATE aliases question and reply questions astir loops, recursion, sorting, searching, and nested operations.


Core Concepts

Big O notation focuses connected maturation rate, not nonstop stopwatch time. The aforesaid codification whitethorn tally faster connected 1 laptop and slower connected different server, but its maturation shape usually stays the same. This is why interviewers inquire for Big O: it shows whether your solution scales erstwhile input size grows from thousands to millions.

1.Asymptotic Bounds

Big O, Big Omega, and Big Theta are asymptotic notations. Big O gives an precocious bound, Ω gives a little bound, and Θ gives a tight bound. In interviews, candidates usually opportunity “the clip complexity is O(n)” erstwhile they mean the worst-case precocious bound, but the notation itself is broader than worst lawsuit alone.

Familiar example: opening the first connection successful a telephone inbox is O(1), while scanning each messages for a circumstantial keyword is O(n). Industry example: a banking fraud strategy whitethorn guarantee astatine slightest Ω(n) activity if it must inspect each transaction once, and it whitethorn beryllium Θ(n) if it ever performs precisely 1 pass.

GATE and interviews often inquire the quality betwixt O, Ω, and Θ. Standard answer: O is an asymptotic precocious bound, Ω is an asymptotic little bound, and Θ is simply a tight bound erstwhile some precocious and little bounds are the aforesaid order.

Code Example

2.Simplification Rules

Big O ignores machine-specific constants and lower-order position because maturation complaint dominates astatine ample input sizes. If an algorithm takes 3n² + 10n + 50 operations, its Big O is O(n²). The n² word yet becomes overmuch larger than the linear and changeless terms.

Familiar example: checking each pairs of photos successful a assemblage dominates a one-time setup step. Industry example: an e-commerce proposal occupation that compares each merchandise brace has O(n²) brace activity moreover if it besides loads a configuration record successful O(1).

Drop constants, driblet lower-order terms, and support the fastest-growing term. O(2n) becomes O(n), O(n² + n) becomes O(n²), and O(500) becomes O(1).

Code Example

3.Constant Time

O(1) intends the number of operations does not turn pinch input size. It does not mean the cognition takes 1 nanosecond; it intends the activity stays bounded by a constant. Dictionary lookup, array indexing, and reference a stack apical are emblematic examples.

Familiar example: checking the equilibrium shown astatine the apical of a mobile wallet surface does not require scanning each past payments. Industry example: a PAN verification work tin fetch cached metadata by PAN number utilizing a hash map-style cardinal lookup successful expected O(1) time.

Code Example

4.Logarithmic Time

O(log n) appears erstwhile each measurement removes a fixed fraction of the remaining input. Binary hunt is the classical case: cheque the middle, discard half, and repeat. If the input doubles, the number of other steps increases only slightly.

Familiar example: searching a connection successful a sorted dictionary by many times opening the mediate page. Industry example: an IRCTC-style booking strategy tin hunt a sorted train-number scale utilizing binary search-like logic alternatively of scanning each train record.

Binary hunt is O(log n) only erstwhile the hunt abstraction is sorted aliases system truthful that half tin beryllium safely discarded. Applying binary hunt to unsorted information gives incorrect results, not conscionable mediocre performance.

Code Example

5.Double Logarithmic Time

O(log log n) grows moreover much slow than O(log n). It appears successful specialised algorithms wherever the scale aliases campaigner scope grows highly fast, often by repeated exponentiation aliases squaring. Beginners spot it little often, but intermediate learners should recognise the pattern.

Familiar example: guessing a immense scope wherever each hint lets you jump from 2 to 4 to 16 to 256 and truthful on. Industry example: low-level database indexing aliases precocious integer algorithms whitethorn usage structures wherever lookups impact double-logarithmic position nether circumstantial assumptions.

Code Example

6.Square Root Time

O(√n) appears erstwhile an algorithm only needs to scan up to the quadrate guidelines of the input value. A communal illustration is primality testing: if n has a facet larger than √n, it must besides person a matching facet smaller than √n.

Familiar example: checking whether a locker count has a divisor by testing only imaginable factors up to its quadrate root. Industry example: a costs consequence work whitethorn usage factor-style checks aliases bucket decomposition wherever scanning √n blocks is capable alternatively of scanning n records.

Code Example

7.Linear Time

O(n) intends the algorithm’s activity grows straight pinch input size. If input doubles, the activity astir doubles. Single-pass validation, summation, filtering, counting, and searching an unsorted database usually autumn into this class.

Familiar example: reference each point successful a market measure to cipher the total. Industry example: a healthcare exertion scanning today’s assignment records to count completed consultations performs 1 cheque per appointment, truthful the clip complexity is O(n).

Code Example

8.Linearithmic Time

O(n log n) commonly appears successful businesslike comparison-based sorting algorithms specified arsenic merge benignant and heap sort. The algorithm has log n levels of splitting aliases heap adjustment, and each level processes n full elements.

Familiar example: arranging exam reply sheets by rotation number utilizing a divide-and-merge process. Industry example: an ed-tech level sorting lakhs of leaderboard scores efficiently should for illustration O(n log n) sorting complete pairwise O(n²) comparisons.

For comparison-based sorting, O(n log n) is the modular businesslike bound. Python uses Timsort for database sorting, which is highly optimised and has O(n log n) worst-case time.

Code Example

9.Quadratic Time

O(n²) appears erstwhile each point whitethorn request to beryllium compared pinch each different item. Two nested loops complete the aforesaid input are the accustomed signal. Quadratic solutions whitethorn walk for mini n but go risky erstwhile n reaches lakhs.

Familiar example: comparing each impermanent pinch each different impermanent to find copy invitations. Industry example: a Zomato-style edifice matching occupation that compares each edifice pinch each customer penchant without indexing tin go O(n²)-like and expensive.

Code Example

10.Cubic Time

O(n³) appears pinch 3 nested loops complete the aforesaid input size. It is communal successful naive matrix multiplication and immoderate chart algorithms. Cubic clip grows very quickly: expanding n from 100 to 1,000 multiplies the activity by 1,000 times.

Familiar example: trying each operation of 3 players from a squad for a fixed domiciled trio. Industry example: a logistics level evaluating three-way warehouse, truck, and way combinations without optimisation whitethorn accidentally create cubic workloads.

Code Example

11.Binary Exponential Time

O(2ⁿ) appears erstwhile each input point creates 2 branches, usually see aliases exclude. This is communal successful brute-force subset problems. Exponential algorithms go impractical quickly because adding 1 much input tin astir double the work.

Familiar example: choosing each imaginable subsets of dishes for a statement menu. Industry example: an security declare motor trying each operation of optional argumentation clauses without pruning tin look exponential growth.

Do not confuse 2 nested loops pinch O(2ⁿ). Nested loops usually springiness polynomial clip specified arsenic O(n²), while O(2ⁿ) comes from binary branching crossed n decisions.

Code Example

12.K Way Exponential

O(kⁿ) appears erstwhile each of n positions has k choices. If k is 2, it becomes O(2ⁿ); if k is 10, the hunt abstraction is overmuch larger. This shape appears successful brute-force generation, constraint solving, and duty problems.

Familiar example: generating each imaginable 4-digit numeric PINs has 10 choices for each position. Industry example: a SaaS configuration tester that tries each operation of k characteristic settings crossed n modules tin go O(kⁿ) without sampling aliases pruning.

Code Example

13.Factorial Time

O(n!) appears erstwhile an algorithm tries each imaginable ordering. It grows faster than exponential clip for ample n. Permutation procreation and brute-force travelling salesperson hunt are modular examples.

Familiar example: arranging each imaginable seating orders for a wedding table. Industry example: a courier level that tries each imaginable transportation way bid for n stops without move programming aliases heuristics faces factorial growth.

Code Example

14.Independent Inputs

O(n + m) is utilized erstwhile an algorithm processes 2 independent inputs separately. Do not illness it to O(n) unless you cognize m is bounded by n. This is particularly communal successful chart problems, record merges, and multi-source information processing.

Familiar example: reference n WhatsApp contacts and m email contacts to create 1 mixed list. Industry example: a GST invoice reconciliation occupation whitethorn scan n acquisition records and m vendor records erstwhile each earlier matching done a map.

Code Example

15.Product Complexity

O(n × m) appears erstwhile each point from 1 input is compared pinch each point from different input. This is different from O(n²), wherever some loops usually usage the aforesaid input size. Keeping variables abstracted makes your study much accurate.

Familiar example: comparing each book successful 1 support pinch each explanation successful different shelf. Industry example: an ONDC catalog matcher comparing n seller products pinch m purchaser hunt intents without indexing performs product-sized work.

Code Example

For loops successful sequence, adhd complexities. For nested loops, multiply complexities. For independent inputs, support abstracted variables specified arsenic n and m alternatively of forcing everything into n.

Big O Cheat Sheet

Use this large o cheat expanse arsenic a speedy ranking from mostly amended to mostly worse. The nonstop champion prime still depends connected constraints, constants, memory, input distribution, and correctness requirements.

  • Excellent: O(1), O(log log n), O(log n)
  • Usually scalable: O(√n), O(n), O(n log n)
  • Risky for ample n: O(n²), O(n × m), O(n³)
  • Usually impractical without pruning: O(2ⁿ), O(kⁿ), O(n!)
A slower Big O people tin still beryllium acceptable for mini input sizes. For example, O(n²) pinch n = 30 whitethorn beryllium fine, while O(n log n) pinch dense database calls whitethorn still request optimisation.

Learning Path

Build Big O accomplishment by analysing existent code, not by memorising symbols alone. Move from elemental loops to recursion, past to information structures and optimisation trade-offs.


Frequently Asked Questions

What is Big O Notation Explained pinch Examples for Beginners?

Big O notation explains really an algorithm’s clip aliases abstraction grows erstwhile input size grows. For beginners, examples specified arsenic linear hunt O(n), binary hunt O(log n), and brace comparison O(n²) make the thought concrete.

What is clip complexity Big O?

Time complexity large o describes the maturation complaint of execution steps arsenic input size n increases. It does not measurement nonstop seconds because hardware, language, compiler, and web delays tin alteration existent runtime.

What is the quality betwixt O, Ω, and Θ?

O gives an precocious bound, Ω gives a little bound, and Θ gives a tight bound. If an algorithm ever makes 1 walk done n items, its complexity tin beryllium described arsenic Θ(n), while O(n) is still a valid upper-bound statement.

How do I cipher Big O from code?

Count really galore times the main operations tally arsenic input grows. Sequential loops are added, nested loops are multiplied, constants are dropped, and only the ascendant word remains.

When is O(n log n) amended than O(n²)?

O(n log n) is usually amended for ample input sizes because it grows overmuch much slowly. Sorting 1 lakh records pinch an O(n log n) algorithm is acold much applicable than comparing each brace pinch O(n²).

Is O(1) ever faster than O(n)?

Asymptotically, O(1) grows amended than O(n), but existent runtime tin dangle connected constants and implementation details. A costly constant-time web telephone whitethorn beryllium slower than a mini section linear scan for mini inputs.

What is the astir communal Big O mistake?

The astir communal correction is treating each nested loop arsenic O(n²) without checking loop bounds. Two loops complete different inputs whitethorn beryllium O(n × m), while a loop that halves the input each clip is O(log n).

Should I mention champion lawsuit and worst lawsuit successful interviews?

Yes, erstwhile they differ. Linear hunt is O(1) successful the champion lawsuit if the first point matches, but O(n) successful the worst lawsuit if the point is absent aliases astatine the end.


Key Takeaways

Big O notation describes maturation rate, not nonstop runtime. O, Ω, and Θ are upper, lower, and tight asymptotic bounds. The main applicable classes are O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(kⁿ), O(n!), O(n + m), and O(n × m).

For GATE and interviews, the astir tested points are simplification rules, loop summation versus multiplication, binary hunt arsenic O(log n), sorting arsenic O(n log n), brace comparison arsenic O(n²), and recursion branching arsenic exponential aliases factorial.

The earthy adjacent measurement is Complete Guide To Decision Tree Algorithms for Beginners /w Examples, because determination trees thief you use complexity reasoning to existent machine-learning algorithms and recursive splitting.


Further Reading

  • Difference Between Algorithm and Flowchart: Definitions, Table & Examples, useful for revising algorithm practice earlier analysing complexity.
More