VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-number-contain-digit-d/

⇱ Numbers which contain the digit d - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Numbers which contain the digit d

Last Updated : 27 May, 2026

Given two integers n and d. Return an array containing all the numbers between 0 to n that contain the specific digit d.

Examples:

Input: n = 20, d = 5
Output: [5, 15]
Explanation: For number till 20, 5 appears in 5 itself and 15.

Input: n = 50, d = 2
Output: [2, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 42]
Explanation: For number till 50, 2 appears in all these numbers.

[Naive Approach] String Conversion - O(n⨯logn) Time and O(logn) Auxiliary Space

Convert every number i into a string and use built-in string search functions to check if the character 'd' exists inside it.


Output
7 17 27 37 47 

[Expected Approach] Digit Extraction - O(n⨯logn) Time and O(1) Auxiliary Space

We can iterate through all numbers from 0 up to n. For every number, we can repeatedly extract its last digit using the modulo operator (%10). If that extracted digit matches our target digit d, we immediately add the number to our result list. If it doesn't match, we strip that last digit away using integer division (/10) and check the next digit, continuing until the number becomes 0.

  • Create an empty array to store the valid numbers.
  • Loop through every integer i from 0 to n.
  • For each integer i, create a temporary variable num = i.
  • Run a while (num > 0) loop.
  • Check if the last digit matches d (num % 10 == d). If it does, add i to the result list and break the loop .
  • Otherwise, remove the last digit by setting num = num / 10.

Output
7 17 27 37 47 


Comment