Problem 1201

Abstract / Summary

Given a range and two divisors, count numbers divisible by either divisor within that range.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1201.py

class Solution:
    def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
        a, b, c = sorted([a, b, c])

        if c % a == 0 or c % b == 0:
            c = 10**10 # larger than any result
        if b % a == 0:
            b, c = c, 10**10

        ab = a*b // gcd(a, b)
        bc = b*c // gcd(b, c)
        ac = a*c // gcd(a, c)
        abc = a*b*c // gcd(a, b, c)

        def ugly(guess):
            one = guess // a  + guess // b  + guess // c
            two = guess // ab + guess // bc + guess // ac
            three = guess // abc
            return one - two + three

        result = n * a
        step   = result // 2
        while step > 1:
            if ugly(result) >= n:
                result -= step
            else:
                result += step

            step //= 2

        while ugly(result) >= n:
            result -= 1
        while ugly(result) < n:
            result += 1

        return result
36 lines | 984 bytes | submitted September 2, 2023 | GitHub   3% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 32% (100k+ submissions).

Typical patterns to solve this problem:
  • Binary Search
  • Combinatorics
  • Math
  • Number Theory
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The nthUglyNumber method returns the n-th positive integer that is divisible by at least one of the three given factors a, b, or c. The implementation first normalizes the factors, pre-computes the least common multiples needed for inclusion-exclusion, defines a helper that counts how many “ugly” numbers are ≤ a guess, and then performs a fast search that converges on the exact answer.

Normalization of Input

a, b, c = sorted([a, b, c])

if c % a == 0 or c % b == 0:
    c = 10**10          # larger than any result
if b % a == 0:
    b, c = c, 10**10

The three divisors are sorted so that a ≤ b ≤ c. When a larger divisor is a multiple of a smaller one, it can never be the minimal divisor that contributes a new ugly number. The code replaces such redundant divisors with a sentinel value (10**10) that exceeds any possible answer, effectively removing them from the counting logic while keeping the three-variable interface intact.

Least Common Multiple Computations

ab = a*b // gcd(a, b)
bc = b*c // gcd(b, c)
ac = a*c // gcd(a, c)
abc = a*b*c // gcd(a, b, c)

The pairwise and triple least common multiples are derived using the greatest common divisor. These values are essential for the inclusion-exclusion formula that follows, allowing the algorithm to count numbers divisible by multiple factors without double-counting.

Inclusion-Exclusion Helper

def ugly(guess):
    one = guess // a  + guess // b  + guess // c
    two = guess // ab + guess // bc + guess // ac
    three = guess // abc
    return one - two + three

For any guess, ugly(guess) returns the count of integers ≤ guess that are divisible by at least one of the three factors. The formula adds the individual counts (one), subtracts the counts of numbers counted twice (two), and adds back the numbers counted three times (three). This exact count drives the search for the n-th ugly number.

Search Strategy

The algorithm starts with a generous upper bound based on the smallest factor:

result = n * a
step   = result // 2

A halving step size is then used to perform a binary-like descent:

while step > 1:
    if ugly(result) >= n:
        result -= step
    else:
        result += step
    step //= 2

At each iteration the step size is halved, and the direction is chosen by comparing the current count with n. This quickly narrows the interval containing the target value.

Two final linear adjustments guarantee exactness:

while ugly(result) >= n:
    result -= 1
while ugly(result) < n:
    result += 1

The first loop backs off if the current result overshoots the n-th ugly number, and the second loop steps forward if it undershoots. After these loops, result is precisely the smallest integer whose count matches n.

Edge Cases Handled

When any divisor is a multiple of another, the redundant divisor is replaced by the sentinel 10**10. This ensures that the inclusion-exclusion calculation never counts numbers that could only be produced by a divisor that is already covered by a smaller one. The sentinel is large enough that guess // sentinel evaluates to zero for any realistic guess, effectively removing the term from the count without altering the algorithmic flow.

The initial bound result = n * a works even when a is the smallest divisor, guaranteeing that the n-th ugly number cannot exceed this product. The halving loop’s condition step > 1 prevents an infinite loop when the step size reaches zero, and the subsequent linear adjustments handle the final off-by-one situation that can arise from the coarse halving phase.

Performance Optimizations

Sorting the divisors once at the start reduces the number of conditional checks needed later. Replacing redundant divisors with a sentinel eliminates unnecessary division operations in the ugly helper, because any division by the sentinel yields zero. Pre-computing the pairwise and triple LCMs avoids repeated GCD calculations inside the counting loop.

The search uses a geometric reduction of the step size (step //= 2), which converges in logarithmic iterations relative to the initial bound. This approach avoids a full binary search on a monotonic predicate while still achieving a comparable number of evaluations. The final linear sweeps are bounded by at most one step of the halving phase, ensuring that they add only a constant amount of work.

All arithmetic stays in integer domain, leveraging Python’s fast integer division and multiplication, and the algorithm avoids any auxiliary data structures, keeping the runtime footprint minimal.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant collection of magical building blocks that grow in groups of three. Some grow in groups of size a, some in groups of size b, and others in size c. The task is to find the specific number that belongs to one of these groups when everything is sorted from smallest to largest.

First, the code organizes the groups so the smallest numbers are easy to spot. It ignores groups that are already contained inside other groups because those would just be extra work.

Next, it calculates helpful shortcuts for finding overlaps. If a number is a multiple of two different sizes, it counts it in a special way so the same space is not counted twice.

To find the right answer, the code plays a guessing game. It starts with a big guess and checks how many numbers are in the groups up to that point. If the count is too high, the guess moves down. If it is too low, the guess moves up. By constantly narrowing the search, it gets closer and closer to the exact number.

Finally, once the guess is very close, it checks the neighboring numbers one by one to make sure it has landed on the perfect spot where the count matches exactly what is needed.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.69 | σ = 1.86

Complexity Analysis

Time: logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
26 links | 14 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 4 medium
8 solutions   September 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality