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.
Table of Content
[Naive Approach] String Conversion - O(n⨯logn) Time and O(logn) Auxiliary Space
Convert every number
iinto a string and use built-in string search functions to check if the character'd'exists inside it.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// helper function to check if a number contains the digit d using string method
bool isDigitPresent(int num, int d)
{
// convert number and digit to strings
string numStr = to_string(num);
string dStr = to_string(d);
// check if the digit string is found inside the number string
if (numStr.find(dStr) != string::npos)
{
return true;
}
return false;
}
// function to return an array of all valid numbers
vector<int> findNumbers(int n, int d)
{
vector<int> res;
// check all numbers one by one
for (int i = 0; i <= n; i++)
{
// checking for digit
if (isDigitPresent(i, d))
{
res.push_back(i);
}
}
return res;
}
int main()
{
int n = 47, d = 7;
vector<int> v = findNumbers(n, d);
if (!v.empty())
{
for (int it : v)
{
cout << it << " ";
}
cout << endl;
}
else
cout << -1 << endl;
return 0;
}
import java.util.*;
public class Solution {
// helper function to check if a number contains the
// digit d using string method
public boolean isDigitPresent(int num, int d)
{
// convert number and digit to strings
String numStr = String.valueOf(num);
String dStr = String.valueOf(d);
// check if number string contains the digit string
return numStr.contains(dStr);
}
// function to return an array of all valid numbers
public List<Integer> findNumbers(int n, int d)
{
List<Integer> res = new ArrayList<>();
// check all numbers one by one
for (int i = 0; i <= n; i++) {
// checking for digit
if (isDigitPresent(i, d)) {
res.add(i);
}
}
return res;
}
public static void main(String[] args)
{
int n = 47;
int d = 7;
Solution sol = new Solution();
List<Integer> v = sol.findNumbers(n, d);
if (!v.isEmpty()) {
for (int it : v) {
System.out.print(it + " ");
}
System.out.println();
}
else {
System.out.println("-1");
}
}
}
class Solution:
# helper function to check if a number contains the digit d using string method
def is_digit_present(self, num, d):
# convert number and digit to string and check inclusion
return str(d) in str(num)
# function to return a list of all valid numbers
def findNumbers(self, n, d):
res = []
# check all numbers one by one
for i in range(n + 1):
# checking for digit
if self.is_digit_present(i, d):
res.append(i)
return res
# driver code
if __name__ == '__main__':
n = 47
d = 7
sol = Solution()
v = sol.findNumbers(n, d)
if v:
print(" ".join(map(str, v)))
else:
print("-1")
using System;
using System.Collections.Generic;
class Solution {
// helper function to check if a number contains the
// digit d using string method
public bool IsDigitPresent(int num, int d)
{
// convert number and digit to string and check
// inclusion
return num.ToString().Contains(d.ToString());
}
// function to return a list of all valid numbers
public List<int> findNumbers(int n, int d)
{
List<int> res = new List<int>();
// check all numbers one by one
for (int i = 0; i <= n; i++) {
// checking for digit
if (IsDigitPresent(i, d)) {
res.Add(i);
}
}
return res;
}
// driver code
static void Main()
{
int n = 47;
int d = 7;
Solution sol = new Solution();
List<int> v = sol.findNumbers(n, d);
if (v.Count > 0) {
Console.WriteLine(string.Join(" ", v));
}
else {
Console.WriteLine("-1");
}
}
}
class Solution {
// helper function to check if a number contains the
// digit d using string method
isDigitPresent(num, d)
{
// convert number and digit to string and check
// inclusion
return num.toString().includes(d.toString());
}
// function to return an array of all valid numbers
findNumbers(n, d)
{
const res = [];
// check all numbers one by one
for (let i = 0; i <= n; i++) {
// checking for digit
if (this.isDigitPresent(i, d)) {
res.push(i);
}
}
return res;
}
}
// small driver code
const n = 47;
const d = 7;
const sol = new Solution();
const v = sol.findNumbers(n, d);
if (v.length > 0) {
console.log(v.join(" "));
}
else {
console.log("-1");
}
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
ifrom 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, addito the result list and break the loop . - Otherwise, remove the last digit by setting num = num / 10.
#include <bits/stdc++.h>
using namespace std;
// returns true if d is present as digit
// helper function to check if a number contains the digit d
bool isDigitPresent(int num, int d) {
// if both the number and the target digit are 0
if (num == 0 && d == 0) {
return true;
}
// extract digits one by one
while (num > 0) {
if (num % 10 == d) {
return true;
}
num /= 10;
}
return false;
}
// function to display the values
vector<int> findNumbers(int n, int d)
{
vector<int> res;
// check all numbers one by one
for (int i = 0; i <= n; i++) {
// checking for digit
if (isDigitPresent(i, d))
res.push_back(i);
}
return res;
}
// Driver code
int main()
{
int n = 47, d = 7;
vector<int> v = findNumbers(n, d);
if(v.size()) for(auto it:v) cout<<it<<" ";
else cout<<-1<<endl;
return 0;
}
import java.util.*;
public class Solution {
// helper function to check if a number contains the
// digit d
public boolean isDigitPresent(int num, int d)
{
// if both the number and the target digit are 0
if (num == 0 && d == 0) {
return true;
}
// extract digits one by one
while (num > 0) {
if (num % 10 == d) {
return true;
}
num /= 10;
}
return false;
}
// function to display the values
public List<Integer> findNumbers(int n, int d)
{
List<Integer> res = new ArrayList<>();
// check all numbers one by one
for (int i = 0; i <= n; i++) {
// checking for digit
if (isDigitPresent(i, d))
res.add(i);
}
return res;
}
// Driver code
public static void main(String[] args)
{
int n = 47, d = 7;
Solution sol = new Solution();
List<Integer> v = sol.findNumbers(n, d);
if (v.size() > 0) {
for (int it : v) {
System.out.print(it + " ");
}
System.out.println();
}
else {
System.out.println(-1);
}
}
}
class Solution:
# returns true if d is present as digit
# helper function to check if a number contains the digit d
def isDigitPresent(self, num, d):
# if both the number and the target digit are 0
if num == 0 and d == 0:
return True
# extract digits one by one
while num > 0:
if num % 10 == d:
return True
num //= 10
return False
# function to display the values
def findNumbers(self, n, d):
res = []
# check all numbers one by one
for i in range(n + 1):
# checking for digit
if self.isDigitPresent(i, d):
res.append(i)
return res
# Driver code
if __name__ == '__main__':
n = 47
d = 7
sol = Solution()
v = sol.findNumbers(n, d)
if len(v) > 0:
for it in v:
print(it, end=" ")
print()
else:
print("-1")
using System;
using System.Collections.Generic;
class Solution {
// helper function to check if a number contains the
// digit d
public bool isDigitPresent(int num, int d)
{
// if both the number and the target digit are 0
if (num == 0 && d == 0) {
return true;
}
// extract digits one by one
while (num > 0) {
if (num % 10 == d) {
return true;
}
num /= 10;
}
return false;
}
// function to display the values
public List<int> findNumbers(int n, int d)
{
List<int> res = new List<int>();
// check all numbers one by one
for (int i = 0; i <= n; i++) {
// checking for digit
if (isDigitPresent(i, d))
res.Add(i);
}
return res;
}
// Driver code placed directly inside the Solution class
static void Main()
{
int n = 47, d = 7;
Solution sol = new Solution();
List<int> v = sol.findNumbers(n, d);
if (v.Count > 0) {
foreach(var it in v)
{
Console.Write(it + " ");
}
Console.WriteLine();
}
else {
Console.WriteLine(-1);
}
}
}
class Solution {
// helper function to check if a number contains the
// digit d
isDigitPresent(num, d)
{
// if both the number and the target digit are 0
if (num === 0 && d === 0) {
return true;
}
// extract digits one by one
while (num > 0) {
if (num % 10 === d) {
return true;
}
num = Math.floor(num / 10);
}
return false;
}
// function to display the values
findNumbers(n, d)
{
let res = [];
// check all numbers one by one
for (let i = 0; i <= n; i++) {
// checking for digit
if (this.isDigitPresent(i, d))
res.push(i);
}
return res;
}
}
// Driver code
let n = 47, d = 7;
let sol = new Solution();
let v = sol.findNumbers(n, d);
if (v.length > 0) {
let output = "";
for (let it of v) {
output += it + " ";
}
console.log(output);
}
else {
console.log(-1);
}
Output
7 17 27 37 47