MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Time Complexity Calculation Rules & Common Runtime Patterns0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
HomeTutorialsData Structures & AlgorithmsTime Complexity Calculation Rules & Common Runtime Patterns
Space Complexity, Auxiliary Memory & Stack vs Heap Allocation

Time Complexity Calculation Rules & Common Runtime Patterns

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

To master technical interviews and algorithm design, you must be able to calculate the exact Big-O time complexity of arbitrary code by sight. This tutorial establishes the 4 fundamental arithmetic rules of Big-O and breaks down common loops, recursion, and nested patterns.


1. Real-World Analogy: Traveling Across Town

Suppose you travel from your house to an international airport:

  1. 1
    You walk 3 minutes to your driveway.
  2. 2
    You drive 45 minutes on the highway.
  3. 3
    You wait 4 hours for an international flight.

When someone asks how long your journey took, you say: "Around 4 to 5 hours." You do not say "4 hours, 45 minutes, and 180 seconds." In Big-O analysis, we drop non-dominant constants and lower-order terms because as journeys scale to days, walking down the driveway contributes virtually zero percentage to the total duration.


2. The 4 Golden Rules of Big-O Calculation

Rule 1: Drop Constants

$O(2n)$, $O(50n)$, and $O(\frac{n}{2})$ all simplify to $O(n)$.

1# Even though there are two separate loops (2n operations), it is O(n)
2for x in items: # n operations
3 print(x)
4for y in items: # n operations
5 print(y)
6# Total: 2n -> O(n)

Rule 2: Different Steps Add Together

If your code does one task followed by a completely different task with different inputs, add their complexities:

1def process_data(list_a, list_b):
2 for a in list_a: # Takes O(a)
3 print(a)
4 for b in list_b: # Takes O(b)
5 print(b)
6# Total Time: O(a + b) [NOT O(n)!]

Rule 3: Nested Steps Multiply

When an inner loop executes once for every single iteration of an outer loop, multiply their complexities:

1for a in list_a: # Runs 'a' times
2 for b in list_b: # Runs 'b' times for each 'a'
3 print(a, b)
4# Total Time: O(a * b)

Rule 4: Drop Non-Dominant Terms

Keep only the term with the steepest asymptotic growth rate:

  • $O(n^2 + n) \implies O(n^2)$
  • $O(n + \log n) \implies O(n)$
  • $O(2^n + n^{100}) \implies O(2^n)$

3. Loop Analysis Patterns

Pattern A: Halving Loop Variables $\implies O(\log n)$

Whenever a loop counter multiplies or divides by a factor on each iteration, the complexity is logarithmic:

1def log_loop(n: int):
2 i = 1
3 while i < n:
4 print(i)
5 i *= 2 # Doubling i means loop runs log2(n) times!

Pattern B: Dependent Inner Loops

1def triangle_pattern(n: int):
2 # Outer runs n times
3 for i in range(n):
4 # Inner runs i times: 0 + 1 + 2 + ... + (n-1) = n*(n-1)/2
5 for j in range(i):
6 print(i, j)
7 # Total: (n^2 - n) / 2 -> Dropping constants & lower term -> O(n^2)

4. Multi-Language Implementations: Sieve of Eratosthenes ($O(n \log \log n)$)

The classical Sieve algorithm calculates all prime numbers up to $n$:

Python 3:

1def count_primes(n: int) -> int:
2 if n <= 2:
3 return 0
4 is_prime = [True] * n
5 is_prime[0] = is_prime[1] = False
6
7 p = 2
8 while p * p < n:
9 if is_prime[p]:
10 for multiple in range(p * p, n, p):
11 is_prime[multiple] = False
12 p += 1
13
14 return sum(is_prime)

Modern JavaScript / TypeScript:

1export function countPrimes(n: number): number {
2 if (n <= 2) return 0;
3 const isPrime = new Uint8Array(n).fill(1);
4 isPrime[0] = 0;
5 isPrime[1] = 0;
6 
7 for (let p = 2; p * p < n; p++) {
8 if (isPrime[p]) {
9 for (let multiple = p * p; multiple < n; multiple += p) {
10 isPrime[multiple] = 0;
11 }
12 }
13 }
14 
15 let count = 0;
16 for (let i = 2; i < n; i++) {
17 if (isPrime[i]) count++;
18 }
19 return count;
20}

5. Dry-Run Step Table: Halving Loop (n = 64)

IterationCounter value (i)Condition (i < 64)Steps Completed
11True1
22True2
34True3
48True4
516True5
632True6
764False (Loop Terminates)$\mathbf{\log_2(64) = 6\text{ steps!}}$

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is the simplified Big-O time complexity of an algorithm whose step count formula is $T(n) = 5n^3 + 200n^2 + 10,000$?
Question 2
What is the time complexity of the following code snippet?
PythonCode Snippet
1i = n
2while i > 1:
3 i = i // 2
Question 3
If a function iterates over an array of size $A$ in an outer loop, and inside it iterates over an entirely separate array of size $B$, what is the time complexity?
Question 4
What is the sum of the series $1 + 2 + 3 + \dots + n$, and what is its Big-O complexity?
Question 5
What common mistake do engineers make when calculating the complexity of built-in functions like string slicing (str[1:]) or array cloning (arr.slice())?

Next Lesson

Space Complexity, Auxiliary Memory & Stack vs Heap Allocation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Introduction to DSA, Big-O, Big-Omega & Big-Theta NotationsSpace Complexity, Auxiliary Memory & Stack vs Heap Allocation

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext