Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Primes

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "204" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given an integer n, return the number of prime numbers that are strictly less than n. Example 1: Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 0 Constraints: 0 <= n <= 5 * 106

Explanation

  • Sieve of Eratosthenes: Use the Sieve of Eratosthenes algorithm to efficiently find all prime numbers less than n. This involves creating a boolean array representing numbers from 0 to n-1, initially marking all as potentially prime, and then iteratively marking the multiples of each prime number as composite (not prime).
    • Optimization: Start the marking of multiples from the square of the prime number. This significantly reduces redundant calculations because all smaller multiples would have already been marked by smaller prime numbers.
    • Counting Primes: After marking all composite numbers, simply count the number of remaining numbers that are marked as prime in the boolean array.
  • Runtime Complexity: O(n log log n), Storage Complexity: O(n)

Code

    def countPrimes(n):
    """
    Counts the number of prime numbers less than a non-negative number, n.

    Args:
        n: A non-negative integer.

    Returns:
        The number of prime numbers less than n.
    """
    if n <= 2:
        return 0

    isPrime = [True] * n
    isPrime[0] = isPrime[1] = False

    for i in range(2, int(n**0.5) + 1):
        if isPrime[i]:
            for j in range(i*i, n, i):
                isPrime[j] = False

    return sum(isPrime)

More from this blog

C

Chatmagic blog

2894 posts