πŸš€ Mastering Time Complexity in Java: A Complete Beginner’s Guide (Part 2)

Welcome back! In Part 1, we learned what Time Complexity is, what Big-O notation means, why constants are ignored, and how to analyze simple loops. We also saw why loops with i++, i += 2, and i += 3 all have O(n) time complexity.

In this part, we’ll answer some of the most confusing questions students have:

  • πŸ€” Is counting backwards different from counting forwards?
  • πŸ€” Is i * 2 < n logarithmic?
  • πŸ€” What exactly is a logarithm?
  • πŸ€” Why does i = i * 2 become O(log n)?
  • πŸ€” What is O(√n) and where is it used?

Let’s begin!


βœ… Example 5 – Decrement by 2

Many students think that counting backwards changes the Time Complexity.

Let’s see whether that’s true.

for(int i = n; i > 0; i = i - 2)
{
    System.out.println(i);
}

Step 1 – Initialization

int i = n;

Runs only once.

Operations = 1


Step 2 – Condition

i > 0

The condition is checked before every iteration and one extra time when it becomes false.


Step 3 – Decrement

i = i - 2;

Suppose

n = 10

The values become

10

8

6

4

2

The loop executes

n / 2

times.


Step 4 – Loop Body

System.out.println(i);

Also executes

n / 2

times.


Total Operations

Initialization

1

Condition

(n/2) + 1

Decrement

n/2

Loop Body

n/2

Total

3n/2 + 2

Ignoring constants,

βœ… Time Complexity = O(n)


πŸ“Œ Key Observation

Whether the loop counts:

i++

or

i--

or

i = i - 2

or

i = i + 5

the complexity remains O(n) because the loop variable changes by a constant amount.


βœ… Example 6 – Is This O(log n)?

This is one of the most common interview questions.

for(int i = 1; i * 2 < n; i++)
{
    System.out.println(i);
}

Many beginners immediately think:

“There is a 2, so it must be logarithmic.”

❌ Wrong!

Let’s analyze it carefully.


Step 1 – Simplify the Condition

The condition is

i Γ— 2 < n

Divide both sides by 2.

i < n / 2

The loop is actually equivalent to

for(int i = 1; i < n/2; i++)

Notice something?

The loop variable still changes like this:

i++

It is not doubling.


Dry Run

Suppose

n = 20

The values of i become

1

2

3

4

5

6

7

8

9

When

i = 10

the condition becomes

10 Γ— 2 = 20

which is false.

The loop executes approximately

n/2

times.

Therefore,

βœ… Time Complexity = O(n)


⚠️ Interview Tip

Always ask yourself:

“What changes the loop variable?”

If the loop variable changes by

i++

or

i += 2

or

i -= 5

the complexity is usually O(n).

Changing the condition does not automatically make the loop logarithmic.


πŸ€” What Exactly is a Logarithm?

Before understanding logarithmic loops, let’s first understand what a logarithm actually means.

Suppose we have

2ΒΉ = 2

2Β² = 4

2Β³ = 8

2⁴ = 16

2⁡ = 32

2⁢ = 64

Now ask this question:

2 raised to what power gives 32?

Answer:

5

Therefore,

logβ‚‚32 = 5

A logarithm simply tells us

How many times must we repeatedly multiply by the same number to reach a target value?


Another Example

Suppose

3ΒΉ = 3

3Β² = 9

3Β³ = 27

3⁴ = 81

Now ask:

3 raised to what power gives 81?

Answer

4

Therefore,

log₃81 = 4

πŸ’‘ Easy Definition

A logarithm answers this question:

“How many times do I repeatedly multiply (or divide) by the same number to reach my destination?”


βœ… Example 7 – Multiplying by 2

for(int i = 1; i < n; i = i * 2)
{
    System.out.println(i);
}

This is completely different from

i = i + 2

Dry Run

Suppose

n = 32

Values become

1

2

4

8

16

32

Notice something?

Each iteration doubles the value.


Mathematical Analysis

Suppose after k iterations

2ᡏ = n

Taking logarithm,

k = logβ‚‚n

Therefore,

βœ… Time Complexity = O(log n)


πŸš€ Why Is This So Fast?

Suppose

n = 1,000,000

A normal loop executes

1,000,000

iterations.

A logarithmic loop executes only about

20

iterations.

That is why algorithms like Binary Search are incredibly fast.


βœ… Example 8 – Dividing by 2

for(int i = n; i > 0; i = i / 2)
{
    System.out.println(i);
}

Dry Run

Suppose

n = 64

Values become

64

32

16

8

4

2

1

Mathematical Analysis

Suppose after k iterations

n / 2ᡏ = 1

Rearranging,

2ᡏ = n

Taking logarithm,

k = logβ‚‚n

Therefore,

βœ… Time Complexity = O(log n)


πŸ“Œ Important Rule

Whenever the loop variable changes like

i *= 2

or

i *= 3

or

i /= 2

or

i /= 5

the complexity becomes

O(log n)

because the variable changes multiplicatively, not by a fixed amount.


βœ… Example 9 – Square Root Complexity (O(√n))

One of the most common algorithms with O(√n) complexity is checking whether a number is prime.

Consider the following code.

int n = 100;

for(int i = 1; i * i <= n; i++)
{
    System.out.println(i);
}

Step 1 – Initialization

int i = 1;

Runs only once.


Step 2 – Condition

i * i <= n

This means

iΒ² ≀ n

Taking square root on both sides,

i ≀ √n

The loop continues only until the square root of n.


Dry Run

Suppose

n = 100

Values become

1

2

3

4

5

6

7

8

9

10

When

11 Γ— 11 = 121

the condition becomes false.

The loop executes only

10

times.

Notice

√100 = 10

Another Example

Suppose

n = 64

The loop executes

1

2

3

4

5

6

7

8

because

8 Γ— 8 = 64

Again,

√64 = 8

Time Complexity

The loop executes approximately

√n

times.

Therefore,

βœ… Time Complexity = O(√n)


🌟 Why Do Programmers Write i * i <= n?

You may also see

for(int i = 1; i <= Math.sqrt(n); i++)

This is also O(√n).

However, experienced programmers prefer

for(int i = 1; i * i <= n; i++)

because

βœ… It avoids repeatedly calling Math.sqrt().

βœ… It uses integer arithmetic.

βœ… It is the standard interview solution.


🌟 Real-World Example – Prime Number Check

One of the most famous O(√n) algorithms is checking whether a number is prime.

public class PrimeCheck {

    public static void main(String[] args) {

        int n = 97;
        boolean isPrime = true;

        if(n <= 1)
            isPrime = false;

        else {

            for(int i = 2; i * i <= n; i++) {

                if(n % i == 0) {
                    isPrime = false;
                    break;
                }
            }

        }

        if(isPrime)
            System.out.println("Prime Number");
        else
            System.out.println("Not Prime");
    }
}

πŸ€” Why Only Check Up to √n?

Suppose

n = 36

Its factors are

1 Γ— 36

2 Γ— 18

3 Γ— 12

4 Γ— 9

6 Γ— 6

After reaching 6, the factors begin repeating in reverse.

9 Γ— 4

12 Γ— 3

18 Γ— 2

36 Γ— 1

Therefore,

once we’ve checked up to

√36 = 6

there is no need to continue.

This is why Prime Number checking can be done in O(√n) instead of O(n).


🧠 Memory Tricks

Whenever you see

i++
i += 2
i -= 3

➑️ Think

O(n)


Whenever you see

i *= 2
i /= 2
i *= 3

➑️ Think

O(log n)


Whenever you see

i * i <= n

or

Math.sqrt(n)

➑️ Think

O(√n)


πŸ“ Part 2 Summary

In this part, we learned:

βœ… Why decrementing by a constant is still O(n)

βœ… Why i * 2 < n is O(n) and not O(log n)

βœ… What a logarithm really means

βœ… Why i *= 2 becomes O(log n)

βœ… Why i /= 2 is also O(log n)

βœ… What O(√n) means

βœ… Why Prime Number checking uses O(√n)


πŸ“Œ Coming Up in Part 3

In the final part of this guide, we’ll cover:

  • βœ… Nested loops (O(nΒ²))
  • βœ… Triangular loops
  • βœ… O(n log n)
  • βœ… O(nΒ³)
  • βœ… Standard order of Big-O notations
  • βœ… Common interview mistakes
  • βœ… Quick revision table
  • βœ… Final conclusion and practice tips

By the end of Part 3, you’ll have a complete understanding of the most common Time Complexity patterns asked in interviews and university exams.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *