random numbers
unique numbers
number generation
coding
programming

Generate 'n' unique random numbers within a range

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Generating random numbers is easy. Generating n distinct random numbers inside a fixed range adds a second constraint: every value must be unique, and the request must still be efficient for the size of the range.

Validate the Range First

Before choosing an algorithm, make sure the request is even possible. If the range contains fewer values than n, uniqueness cannot be satisfied.

python
1def validate_request(low, high, n):
2    if low > high:
3        raise ValueError("low must be less than or equal to high")
4
5    available = high - low + 1
6    if n > available:
7        raise ValueError("n is larger than the number of available values")

This check should happen before any random generation begins.

Use random.sample in Python

For ordinary application code in Python, random.sample is the cleanest solution. It draws unique values without replacement.

python
1import random
2
3numbers = random.sample(range(10, 51), 5)
4print(numbers)

This returns five distinct integers between 10 and 50, inclusive. It is concise, correct, and usually the best default.

Why sample Is Better Than Repeated Retry Loops

A common beginner solution is to keep generating numbers until a set reaches the desired size:

python
1import random
2
3def unique_numbers_with_set(low, high, n):
4    chosen = set()
5    while len(chosen) < n:
6        chosen.add(random.randint(low, high))
7    return list(chosen)

This works, but it becomes less efficient as n approaches the size of the range because collisions become more frequent. random.sample handles the uniqueness constraint directly and communicates intent more clearly.

When the Range Is Huge

If the numeric range is enormous and n is small, you may still prefer a set-based approach because building a full list of every candidate value may be wasteful in some languages or runtimes.

In Python, range is lazy enough that random.sample(range(...), n) is still a strong option for many large ranges. But the general design lesson remains: choose a method that matches the size relationship between the range and the requested sample.

Cryptographic Randomness

If the numbers are used for security-sensitive purposes such as tokens, codes, or temporary credentials, use secrets instead of random.

python
1import secrets
2
3def secure_unique_numbers(low, high, n):
4    validate_request(low, high, n)
5    chosen = set()
6
7    while len(chosen) < n:
8        chosen.add(secrets.randbelow(high - low + 1) + low)
9
10    return list(chosen)

This still uses a retry loop, but it draws values from a cryptographically stronger source.

Keep Ordering Requirements in Mind

Sometimes "unique random numbers" means:

  • Random selection, output order does not matter
  • Random selection, output should be sorted afterward
  • Random permutation of the selected values

Those are different requirements. For example:

python
1import random
2
3numbers = random.sample(range(1, 21), 5)
4print("draw order:", numbers)
5print("sorted:", sorted(numbers))

Clarify the expected order before you choose the final step.

Common Pitfalls

  • Forgetting to check whether n fits inside the range leads to infinite loops or runtime errors.
  • Using repeated randint calls without a set allows duplicates.
  • Assuming a retry loop is always efficient becomes expensive when the range is almost exhausted.
  • Using random for security-sensitive use cases is a mistake; use secrets instead.
  • Confusing inclusive and exclusive bounds changes the size of the available range.

Summary

  • Validate that the range contains at least n distinct values.
  • In Python, random.sample is usually the simplest and best way to generate unique random numbers within a range.
  • Retry loops with a set work, but they get less efficient as the range fills up.
  • Use secrets instead of random when the numbers have a security purpose.

Course illustration
Course illustration

All Rights Reserved.