easyProgramming Fundamentals

Time & Space Complexity Intro

A nested loop visits every ordered pair (i, j), where both i and j range from 0 to n-1. Print the number of visits without actually running the nested loop.

No external exercise

Work through the cases

3 examples

Input notation

An integer n, where 0 <= n <= 1000000.

Expected result

The number of visits.
Case 1

Input

4

Expected output

16
Case 2

Input

0

Expected output

0
Case 3

Input

1000000

Expected output

1000000000000

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

There are n choices for each of two independent indices, so the visit count is n². Time and extra space: O(1). Java and C++ use a wide integer.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ArrayList<Long> values = new ArrayList<>();
        while (in.hasNextLong()) values.add(in.nextLong());
        long[] a = values.stream().mapToLong(Long::longValue).toArray();
        long n = a[0];
        System.out.println(n * n);
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.