← Back to Algorithms, page 1

algorithms-0001 · Easy fresher

What is Big-O notation? Use it to compare two ways of checking whether a list of exam marks contains a duplicate.

Big-O describes how the work an algorithm does grows as the input size n grows, keeping only the fastest-growing term and ignoring constants. Comparing every pair of marks takes O(n^2) time and O(1) extra space; remembering seen marks in a set takes O(n) average time and O(n) space. The second is faster for large inputs because it trades memory for time.

Full answer

Problem

Given a list marks of integers, return True if any value appears at least twice.

Example: [72, 85, 90, 85] gives True; [1, 2, 3, 4] gives False.

Constraints: 0 <= len(marks) <= 10^5, values fit in a normal integer.

What Big-O measures

Big-O is an upper bound on growth. We count basic steps (comparisons, assignments) as a function of n, then keep only the dominant term. 3n^2 + 5n + 2 becomes O(n^2), because for large n the n^2 part decides everything. Common classes, from fast to slow: O(1), O(log n), O(n), O(n log n), O(n^2), O(2^n), O(n!).

Two quick rules:

  • Sequential steps add: a loop over n followed by another loop over n is O(n + n) = O(n).
  • Nested steps multiply: a loop over n inside a loop over n is O(n x n) = O(n^2).

We usually quote the worst case. Space complexity counts extra memory, not the input itself.

Brute force

Compare every pair (i, j) with i < j. The number of pairs is n(n - 1)/2. For n = 1,000 that is 499,500 comparisons; for n = 100,000 it is about 5 billion. Time O(n^2), extra space O(1).

Optimal approach

Walk through the list once and keep a set of values seen so far. If the current value is already in the set, a duplicate exists. Set lookups and inserts are O(1) on average because a set is a hash table. Total O(n) time, O(n) extra space.

Sorting first and checking neighbours is a middle option: O(n log n) time and O(1) extra space if you may sort in place.

Why it works

A duplicate exists exactly when some value is seen a second time. The set holds every earlier value, so the first repeat is detected the moment it appears.

Complexity

Brute force O(n^2) time, O(1) space. Set version O(n) average time, O(n) space.

Code

python
def has_duplicate_brute(marks):
    """O(n^2) time, O(1) extra space: compare every pair."""
    n = len(marks)
    for i in range(n):
        for j in range(i + 1, n):
            if marks[i] == marks[j]:
                return True
    return False


def has_duplicate_fast(marks):
    """O(n) average time, O(n) extra space: remember what we have seen."""
    seen = set()
    for m in marks:
        if m in seen:
            return True
        seen.add(m)
    return False


def count_pair_comparisons(n):
    """How many comparisons the brute force makes in the worst case: n(n-1)/2."""
    return sum(n - 1 - i for i in range(n))


if __name__ == "__main__":
    for f in (has_duplicate_brute, has_duplicate_fast):
        assert f([]) is False
        assert f([7]) is False
        assert f([72, 85, 90, 85]) is True
        assert f([1, 2, 3, 4]) is False
    assert count_pair_comparisons(10) == 45          # 10 * 9 / 2
    assert count_pair_comparisons(1000) == 499500    # grows like n^2 / 2
    print("all tests passed")

Save as a01_big_o.py and run python3 a01_big_o.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list and one-element list (no duplicates). All values equal. Negative numbers (no special handling needed with a set).

Pattern

Hashing for membership: replace an inner search loop with an O(1) average lookup in a set or dictionary. Many O(n^2) brute forces become O(n) this way.

python
def has_duplicate_brute(marks):
    """O(n^2) time, O(1) extra space: compare every pair."""
    n = len(marks)
    for i in range(n):
        for j in range(i + 1, n):
            if marks[i] == marks[j]:
                return True
    return False


def has_duplicate_fast(marks):
    """O(n) average time, O(n) extra space: remember what we have seen."""
    seen = set()
    for m in marks:
        if m in seen:
            return True
        seen.add(m)
    return False


def count_pair_comparisons(n):
    """How many comparisons the brute force makes in the worst case: n(n-1)/2."""
    return sum(n - 1 - i for i in range(n))


if __name__ == "__main__":
    for f in (has_duplicate_brute, has_duplicate_fast):
        assert f([]) is False
        assert f([7]) is False
        assert f([72, 85, 90, 85]) is True
        assert f([1, 2, 3, 4]) is False
    assert count_pair_comparisons(10) == 45          # 10 * 9 / 2
    assert count_pair_comparisons(1000) == 499500    # grows like n^2 / 2
    print("all tests passed")

Both versions plus a helper that counts brute-force comparisons, so the n(n - 1)/2 formula is checked by a test.

Complexity

Time: O(n^2) brute force; O(n) average with a set. Space: O(1) brute force; O(n) with a set. Set operations are O(1) on average; adversarial hash collisions can degrade them, which is rarely a concern in interviews.

By level

Fresher: Explains what Big-O means with simple loop examples. Analyses the pair-checking version as O(n^2) and the set version as O(n) with extra space. Should be able to count the comparisons for a list of 4 marks by hand.

Mid: Derives n(n - 1)/2, explains average versus worst case for hashing and gives the O(n log n) sort-based option. Chooses an approach from the constraints. Explains why hash lookups are average O(1) rather than guaranteed.

Senior: Discusses when constants and memory matter more than Big-O, for example cache behaviour or memory limits for 10^9 values. Mentions streaming or probabilistic options such as Bloom filters when the set would not fit in memory. Can say when the O(n^2) version is acceptable, for example a list of 20 items checked once.

Key points

  • Big-O keeps the dominant term and drops constants
  • Sequential steps add, nested loops multiply
  • Brute force pair checking is n(n - 1)/2 comparisons, O(n^2)
  • A set turns the inner search into an O(1) average lookup
  • Faster time often costs extra space

Common mistakes

  • Saying O(2n) instead of simplifying to O(n)
  • Forgetting that a set uses O(n) extra memory
  • Calling the set version O(1) overall
  • Counting the input itself as extra space

Follow-ups

  • What is the complexity if you sort first and compare neighbours?
  • What is the difference between average and worst case for a hash set?
  • What is the Big-O of binary search, and why?

Tips

  • Count the operations out loud for a small n, then generalise
  • Always state both time and space
  • Name the trade-off when you add a data structure

Evaluation rubric

  • Defines Big-O as growth rate with constants dropped
  • Correctly analyses both versions
  • States space as well as time
  • Mentions the sorting alternative or the average-case caveat