Number Patterns
Ascending Order
Algorithm
Mathematics
Coding Challenge

Print all numbers whose nonzero digits are in ascending order

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

This problem asks for numbers whose nonzero digits appear in strictly increasing order from left to right. Zero digits are ignored for the ordering check, so a number like 30479 is valid because the nonzero subsequence is 3, 4, 7, 9.

Define the Rule Precisely

The phrase "nonzero digits are in ascending order" needs a precise interpretation:

  • scan the digits from left to right
  • ignore zeros
  • every remaining digit must be greater than the previous nonzero digit

That means:

  • '123 is valid'
  • '12039 is valid because the nonzero digits are 1, 2, 3, 9'
  • '155 is not valid because the digits are not strictly increasing'
  • '9071 is not valid because 9 then 7 decreases'

Single-digit numbers are always valid, and a number containing only zeros is usually handled according to the surrounding problem statement.

Simple Checking Function

The easiest way to solve the problem for a range is to write a helper that tests one number.

python
1def has_ascending_nonzero_digits(n):
2    last = -1
3
4    for ch in str(abs(n)):
5        digit = int(ch)
6        if digit == 0:
7            continue
8        if digit <= last:
9            return False
10        last = digit
11
12    return True
13
14
15for number in range(1, 60):
16    if has_ascending_nonzero_digits(number):
17        print(number)

This is clear and correct. For many coding-challenge inputs, that is all you need.

Time Complexity of the Direct Approach

If you check every number from 1 to N, the cost is proportional to the number of digits in each number. That gives roughly:

  • 'O(d) work per number, where d is digit count'
  • 'O(N * d) total work for the range'

That is fine for moderate ranges, but if the upper bound is very large, generating only valid numbers can be more efficient.

Constructing Valid Numbers Instead of Filtering

A better idea is to build valid digit sequences directly. Since nonzero digits must be strictly increasing, each nonzero digit can appear at most once, and the allowed sequences come from digits 1 through 9.

One recursive approach is:

  • choose the next digit greater than the previous nonzero digit
  • optionally place zeros between chosen digits
  • stop when you reach the desired length or value limit

Here is a simpler constructive version that generates numbers with no zero insertion. It demonstrates the main combinatorial idea clearly.

python
1def generate_increasing_numbers(start_digit=1, current=""):
2    if current:
3        yield int(current)
4
5    for digit in range(start_digit, 10):
6        yield from generate_increasing_numbers(digit + 1, current + str(digit))
7
8
9result = sorted(generate_increasing_numbers())
10print(result[:20])

This produces values such as:

  • '1'
  • '2'
  • '12'
  • '13'
  • '123'
  • '124'

To support embedded zeros, you would extend the generation logic with controlled zero placement, but the same increasing-digit principle remains.

Practical Range-Based Solution

Most interview and contest versions of the problem ask for all numbers in a range. For that version, filtering with a helper function is usually the best balance of clarity and performance.

python
1def print_valid_numbers(limit):
2    valid = []
3    for number in range(1, limit + 1):
4        if has_ascending_nonzero_digits(number):
5            valid.append(number)
6    return valid
7
8
9print(print_valid_numbers(150))

This is easy to test and easy to adapt.

Edge Cases

A robust solution should decide how to treat:

  • zero itself
  • negative numbers
  • repeated nonzero digits
  • numbers with many zeros between valid digits

For example, 1008 is valid because the nonzero digits are 1, 8, which are increasing. But 8801 is invalid because the nonzero sequence begins 8, 8, which is not strictly increasing.

If the problem definition uses non-decreasing order instead of strictly increasing order, then the comparison changes from digit <= last to digit < last.

Why a String-Based Solution Is Fine

Some people try to solve digit problems only with division and modulo operations. That works, but it often makes left-to-right reasoning harder. For this problem, string conversion is perfectly reasonable unless the environment specifically forbids it.

A math-based version is also possible, but you would usually need to reverse the digits or store them temporarily so you can process them in the original order.

Common Pitfalls

Forgetting to ignore zeros changes the problem and incorrectly rejects values like 10239.

Using a non-strict comparison the wrong way can accidentally allow repeated digits such as 122.

Scanning digits from right to left with modulo arithmetic without compensating for the reversed order produces incorrect results.

Assuming the problem means the entire number must be sorted, rather than only the nonzero digits, leads to wrong outputs.

Summary

  • Ignore zeros and require the remaining digits to be strictly increasing from left to right.
  • A helper function plus a loop over the range is the simplest correct solution.
  • The direct filtering approach runs in O(N * d) for numbers up to N.
  • For very large search spaces, constructive generation can avoid checking obviously invalid numbers.
  • Be explicit about whether the order must be strict or merely non-decreasing.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.