Open In App

Print all possible combinations of the string by replacing ‘$’ with any other digit from the string

Improve
Improve
Like Article
Like
Save
Share
Report

Given a number as a string where some of the digits are replaced by a ‘$’, the task is to generate all possible number by replacing the ‘$’ with any of the digits from the given string.
Examples: 

Input: str = “23$$” 
Output: 
2322 
2323 
2332 
2333
Input: str = “$45” 
Output: 
445 
545 

Approach:  

  • Find all the combinations of the string by replacing the character $ with any of the digits of the string, for this check if the current character is a digit if yes then store this character into an array pre[] then recursively find all of its combinations else if current character is a ‘$’ then replace it with the digits stored in the array and recursively find all the combinations.
  • To find the all possible numbers initialize array set[] that stores all the possible numbers, to generate numbers take two nested loop outer loop is for input string and inner loop is for array set[] that stores all the possible combinations of the numbers. Initialize the boolean flag to check if character of the input string is already present in set[] or not if character of the input string is already present in set[] then set flag = false else if flag is true then move the current character of the input string to set[] and recursively find all the combinations of the input string and store it in the array set[]. Finally print each number from the array set[]

Below is the implementation of the above approach: 

C




// C implementation of the approach
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#define MAX 20
#define DIGITS 10
 
// Array to store all the
// possible numbers
char set[DIGITS];
 
// Index to set[] element
int end;
 
// Function to find all the combinations
// of the string by replacing '$' with
// the other digits of the string
void combinations(char* num, char* pre, int curr, int lvl)
{
 
    // Check if current length is less than
    // the length of the input string
    if (curr < strlen(num)) {
 
        // If current character is a digit
        // then store digit into pre[] and
        // recursively find all the combinations
        if (num[curr] >= '0' && num[curr] <= '9') {
            pre[lvl] = num[curr];
            combinations(num, pre, curr + 1, lvl + 1);
        }
 
        // If current character is a '$' then replace
        // it with the other digits of the string and
        // recursively find all the combinations
        // Else go to the next character and
        // recursively find all the combinations
        else if (num[curr] == '$')
            for (int i = 0; i < end; i++) {
                pre[lvl] = set[i];
                combinations(num, pre, curr + 1, lvl + 1);
            }
        else
            combinations(num, pre, curr + 1, lvl);
    }
 
    // Print the array pre[]
    else {
        pre[lvl] = '\0';
        printf("%s\n", pre);
    }
}
 
// Function to find all the numbers formed
// from the input string by replacing '$' with
// all the digits of the input string
int findNumUtil(char num[])
{
    // Array that stores the digits before
    // the character $ in the input string
    char pre[MAX];
 
    end = 0;
 
    // Traverse the input string and check if
    // the current character is a digit
    // if it is then set flag to true
    for (int i = 0; i < strlen(num); i++)
        if (num[i] >= '0' && num[i] <= '9') {
            bool flag = true;
 
            // Check if current character of the input
            // string is already present in the array set[]
            // then set flag to false
            for (int j = 0; j < end; j++)
                if (set[j] == num[i])
                    flag = false;
 
            // Flag is true then store the character
            // into set[] and recursively find all
            // the combinations of numbers and store
            // it in the set[] array
 
            if (flag == true)
                set[end++] = num[i];
        }
 
    combinations(num, pre, 0, 0);
 
    return 0;
}
 
// Function to print all the combinations
// of the numbers by replacing '$' with
// the other digits of the input string
int findNum(char* num, int* result_count)
{
    int i;
    if (num[i]) {
        result_count[i] = findNumUtil(num);
        return (result_count[i]);
    }
    return 0;
}
 
// Driver code
int main()
{
    char num[MAX] = "23$$";
    int result_count[MAX];
 
    findNum(num, result_count);
 
    return 0;
}


C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 20
#define DIGITS 10
 
// Array to store all the
// possible numbers
string st(DIGITS,'0');
 
// Index to st[] element
int ed;
 
// Function to find all the combinations
// of the string by replacing '$' with
// the other digits of the string
void combinations(string& num, string& pre, int curr, int lvl)
{
 
    // Check if current length is less than
    // the length of the input string
    if (curr < (int)num.length()) {
 
        // If current character is a digit
        // then store digit into pre[] and
        // recursively find all the combinations
        if (num[curr] >= '0' && num[curr] <= '9') {
            pre[lvl] = num[curr];
            combinations(num, pre, curr + 1, lvl + 1);
        }
 
        // If current character is a '$' then replace
        // it with the other digits of the string and
        // recursively find all the combinations
        // Else go to the next character and
        // recursively find all the combinations
        else if (num[curr] == '$')
            for (int i = 0; i < ed; i++) {
                pre[lvl] = st[i];
                combinations(num, pre, curr + 1, lvl + 1);
            }
        else
            combinations(num, pre, curr + 1, lvl);
    }
 
    // Print the array pre[]
    else {
        pre[lvl] = '\0';
        cout << pre << '\n';
    }
}
 
// Function to find all the numbers formed
// from the input string by replacing '$' with
// all the digits of the input string
int findNumUtil(string& num)
{
    // Array that stores the digits before
    // the character $ in the input string
    string pre((int)num.length(),'0');
 
    ed = 0;
 
    // Traverse the input string and check if
    // the current character is a digit
    // if it is then set flag to true
    for (int i = 0; i < num.length(); i++)
        if (num[i] >= '0' && num[i] <= '9') {
            bool flag = true;
 
            // Check if current character of the input
            // string is already present in the array set[]
            // then set flag to false
            for (int j = 0; j < ed; j++)
                if (st[j] == num[i])
                    flag = false;
 
            // Flag is true then store the character
            // into st[] and recursively find all
            // the combinations of numbers and store
            // it in the st[] array
 
            if (flag == true)
                st[ed++] = num[i];
        }
 
    combinations(num, pre, 0, 0);
 
    return 0;
}
 
// Function to print all the combinations
// of the numbers by replacing '$' with
// the other digits of the input string
int findNum(string& num, vector<int>& result_count)
{
    int i;
    if (num[i]) {
        result_count[i] = findNumUtil(num);
        return (result_count[i]);
    }
    return 0;
}
 
// Driver code
int main()
{
    string num;
      num = "23$$";
    vector<int> result_count(MAX);
 
    findNum(num, result_count);
 
    return 0;
}


Python3




# Python3 implementation of the approach
 
 
MAX=20
DIGITS=10
 
# Array to store all the
# possible numbers
st=['0']*DIGITS
pre=[]
 
# Index to st[] element
ed=0
 
# Function to find all the combinations
# of the string by replacing '$' with
# the other digits of the string
def combinations(curr, lvl):
    global num,pre
 
    # Check if current length is less than
    # the length of the input string
    if (curr < len(num)):
 
        # If current character is a digit
        # then store digit into pre[] and
        # recursively find all the combinations
        if (num[curr] >= '0' and num[curr] <= '9'):
            pre[lvl] = num[curr]
            combinations(curr + 1, lvl + 1)
 
        # If current character is a '$' then replace
        # it with the other digits of the string and
        # recursively find all the combinations
        # Else go to the next character and
        # recursively find all the combinations
        elif (num[curr] == '$'):
            for i in range(ed):
                pre[lvl] = st[i]
                combinations(curr + 1, lvl + 1)
        else:
            combinations(curr + 1, lvl)
 
    # Print array pre[]
    else:
        print(''.join(pre))
 
# Function to find all the numbers formed
# from the input string by replacing '$' with
# all the digits of the input string
def findNumUtil():
    # Array that stores the digits before
    # the character $ in the input string
    global pre,ed
    pre=['0']*len(num)
 
    ed = 0
 
    # Traverse the input string and check if
    # the current character is a digit
    # if it is then set flag to True
    for i in range(len(num)):
        if (num[i] >= '0' and num[i] <= '9'):
            flag = True
 
            # Check if current character of the input
            # string is already present in the array set[]
            # then set flag to False
            for j in range(ed):
                if (st[j] == num[i]):
                    flag = False
 
            # Flag is True then store the character
            # into st[] and recursively find all
            # the combinations of numbers and store
            # it in the st[] array
 
            if flag:
                st[ed] = num[i]
                ed+=1
 
    combinations(0, 0)
 
    return 0
 
# Function to print all the combinations
# of the numbers by replacing '$' with
# the other digits of the input string
def findNum(result_count):
    i=0
    if (num[i]):
        result_count[i] = findNumUtil()
        return (result_count[i])
    return 0
 
# Driver code
if __name__ == '__main__':
    num = "23$$"
    result_count=[0]*MAX
 
    findNum(result_count)


Java




/*package whatever //do not write package name here */
 import java.util.*;
import java.io.*;
 
class GFG {
    public static void main(String args[]) {
      String s = "23$$";
      // converting string to char array
      char[] arr = s.toCharArray();
      //store the digits of string in store which is a set, to use it for replacing '$'
         Set<Character> store=new HashSet<>();
      for(int i=0; i<arr.length ;i++){
        // if the current char is not '$' add it to the store set
          if(arr[i] !='$') store.add(arr[i]);
      }
      //recursing everytime to get a possible combination of digits for '$'
     combinations(0,arr,store);
    }
   
   
    public static void combinations(int idx, char[] arr , Set<Character> store){
      //if the current index is greater than the char array length print the current string and return
        if(idx>=arr.length){
            String ans = String.valueOf(arr);
            System.out.println(ans);
            return;
        }
      //if the char at current index is '$' replace it with digits in store
      //using for loop we can replace current '$' with all possible digits
        if(arr[idx]=='$'){
 
            for(char c:store){
             // replace the character having '$' with one of the digit from the string
              //and recur in the combination function
                arr[idx] = c;
                combinations(idx+1, arr,store);
               
                arr[idx] = '$';
            }
 
        }else{
           combinations(idx+1, arr,store);
        }
    }
}


Javascript




const MAX = 20;
const DIGITS = 10;
 
// Array to store all the possible numbers
const st = Array(DIGITS).fill('0');
let pre = [];
 
// Index to st[] element
let ed = 0;
 
// Function to find all the combinations of
// the string by replacing '$' with the
// other digits of the string
function combinations(curr, lvl)
{
 
  // Check if current length is
  // less than the length of the input string
  if (curr < num.length)
  {
   
    // If current character is a digit
    // then store digit into pre[] and
    // recursively find all the combinations
    if (num[curr] >= '0' && num[curr] <= '9') {
      pre[lvl] = num[curr];
      combinations(curr + 1, lvl + 1);
    }
     
    // If current character is a '$' then
    // replace it with the other digits of
    // the string and recursively find all the combinations
    // Else go to the next character and
    // recursively find all the combinations
    else if (num[curr] == '$') {
      for (let i = 0; i < ed; i++) {
        pre[lvl] = st[i];
        combinations(curr + 1, lvl + 1);
      }
    } else {
      combinations(curr + 1, lvl);
    }
  }
  // Print array pre[]
  else {
    console.log(pre.join(''));
  }
}
 
// Function to find all the numbers
// formed from the input string by
// replacing '$' with all the digits of the input string
function findNumUtil() {
 
  // Array that stores the digits
  // before the character $ in the input string
  pre = Array(num.length).fill('0');
  ed = 0;
 
  // Traverse the input string and check
  // if the current character is a digit
  // if it is then set flag to True
  for (let i = 0; i < num.length; i++) {
    if (num[i] >= '0' && num[i] <= '9') {
      let flag = true;
 
      // Check if current character of
      / the input string is already present
      // in the array set[] then set flag to False
      for (let j = 0; j < ed; j++) {
        if (st[j] == num[i]) {
          flag = false;
        }
      }
 
      // Flag is True then store the character
      // into st[] and recursively find all the
      // combinations of numbers and store it in the st[] array
      if (flag) {
        st[ed] = num[i];
        ed++;
      }
    }
  }
 
  combinations(0, 0);
  return 0;
}
 
// Function to print all the combinations of
// the numbers by replacing '$' with the
// other digits of the input string
function findNum(result_count) {
  let i = 0;
  if (num[i]) {
    result_count[i] = findNumUtil();
    return result_count[i];
  }
  return 0;
}
 
// Driver code
let num = "23$$";
let result_count = Array(MAX).fill(0);
 
findNum(result_count);


C#




// c# code for the above approach
using System;
 
public class GFG {
    const int MAX = 20;
    const int DIGITS = 10;
 
    // Array to store all the possible numbers
    static char[] set = new char[DIGITS];
 
    // Index to set[] element
    static int end;
 
    // Function to find all the combinations of the string
    // by replacing '$' with the other digits of the string
    static void Combinations(string num, char[] pre,
                             int curr, int lvl)
    {
        // Check if current length is less than the length
        // of the input string
        if (curr < num.Length) {
            // If current character is a digit then store
            // digit into pre[] and recursively find all the
            // combinations
            if (Char.IsDigit(num[curr])) {
                pre[lvl] = num[curr];
                Combinations(num, pre, curr + 1, lvl + 1);
            }
            // If current character is a '$' then replace it
            // with the other digits of the string and
            // recursively find all the combinations Else go
            // to the next character and recursively find
            // all the combinations
            else if (num[curr] == '$') {
                for (int i = 0; i < end; i++) {
                    pre[lvl] = set[i];
                    Combinations(num, pre, curr + 1,
                                 lvl + 1);
                }
            }
            else {
                Combinations(num, pre, curr + 1, lvl);
            }
        }
        // Print the array pre[]
        else {
            pre[lvl] = '\0';
            Console.WriteLine(new string(pre));
        }
    }
 
    // Function to find all the numbers formed from the
    // input string by replacing '$' with all the digits of
    // the input string
    static int FindNumUtil(string num)
    {
        // Array that stores the digits before the character
        // $ in the input string
        char[] pre = new char[MAX];
 
        end = 0;
 
        // Traverse the input string and check if the
        // current character is a digit if it is then set
        // flag to true
        for (int i = 0; i < num.Length; i++) {
            if (Char.IsDigit(num[i])) {
                bool flag = true;
                // Check if current character of the input
                // string is already present in the array
                // set[] then set flag to false
                for (int j = 0; j < end; j++) {
                    if (set[j] == num[i]) {
                        flag = false;
                        break;
                    }
                }
                // Flag is true then store the character
                // into set[] and recursively find all the
                // combinations of numbers and store it in
                // the set[] array
                if (flag) {
                    set[end++] = num[i];
                }
            }
        }
        Combinations(num, pre, 0, 0);
        return 0;
    }
 
    // Function to print all the combinations of the numbers
    // by replacing '$' with the other digits of the input
    // string
    static int FindNum(string num, int[] result_count)
    {
        if (!String.IsNullOrEmpty(num)) {
            result_count[0] = FindNumUtil(num);
            return result_count[0];
        }
        return 0;
    }
 
    // Driver code
    public static void Main()
    {
        string num = "23$$";
        int[] result_count = new int[MAX];
        FindNum(num, result_count);
    }
}


Output

2322
2323
2332
2333

in-built library/dataset based approach:-

C++




#include <bits/stdc++.h>
using namespace std;
 
// stores all possible non-repetitive combinations
// of string by replacing ‘$’ with any
//    other digit from the string
unordered_set<string> possible_comb;
 
void combinations(string s,int i,int n)
{
   
    if(i==n)
        return;
      // to check whether a string is
      // valid combination
    bool is_combination = true;
    for(int i=0;i<(int)s.length();i++)
    {
        if(s[i]=='$')
        {
            is_combination = false;
            break;
        }
    }
     
    if(is_combination &&  possible_comb.find(s)==possible_comb.end())
    {
        possible_comb.insert(s);
        return;
    }
     
    for(int i=0;i<n;i++)
    {
        if(s[i]=='$')
        {
            for(int j=0;j<n;j++)
            {
                if(s[j]!='$')
                {
                      // replace the character having '$'
                      //    with one of the digit from the
                      // string  and recur in the combination
                      // function
                    s[i] = s[j];
                    combinations(s,j,n);
                    s[i] = '$';
                }
            }
        }
    }
}
 
int main() {
    string s;
    s = "23$$";
      int len = (int)s.size();
    combinations(s,0,len);
    for(auto x:possible_comb)
    {
        cout << x << '\n';
    }
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG
{
   
  // stores all possible non-repetitive combinations
  // of string by replacing ‘$’ with any
  // other digit from the string
  static HashSet<String> possible_comb = new HashSet<>();
 
  static void combinations(String s,int k,int n)
  {
 
    if(k==n)
      return;
    // to check whether a string is
    // valid combination
    boolean is_combination = true;
    for(int i=0;i< s.length();i++)
    {
      if(s.charAt(i)=='$')
      {
        is_combination = false;
        break;
      }
    }
 
    if(is_combination && possible_comb.contains(s)== false)
    {
      possible_comb.add(s);
      return;
    }
 
    for(int i=0;i<n;i++)
    {
      if(s.charAt(i)=='$')
      {
        for(int j=0;j<n;j++)
        {
          if(s.charAt(j)!='$')
          {
            // replace the character having '$'
            // with one of the digit from the
            // string and recur in the combination
            // function
            s = s.substring(0, i) + s.charAt(j) + s.substring(i+1);
            combinations(s,j,n);
            s = s.substring(0, i) + '$' + s.substring(i+1);
          }
        }
      }
    }
  }
 
  // Driver Code
  public static void main(String args[])
  {
    String s = "23$$";
    int len = s.length();
    combinations(s,0,len);
    for(String x:possible_comb)
    {
      System.out.println(x);
    }
  }
 
}
 
// This code is contributed by shinjanpatra.


Python3




# stores all possible non-repetitive combinations
# of string by replacing ‘$’ with any
#    other digit from the string
possible_comb=set()
 
def combinations(s,i,n):
    list_s=list(s)
    if(i==n):
        return
    # to check whether a string is
    # valid combination
    is_combination = True
    for i in range(len(s)):
        if(s[i]=='$'):
            is_combination = False
            break
         
     
     
    if(is_combination and s not in possible_comb):
        possible_comb.add(s)
        return
     
     
    for i in range(n):
        if(s[i]=='$'):
            for j in range(n):
                if(s[j]!='$'):
                      # replace the character having '$'
                      #    with one of the digit from the
                      # string  and recur in the combination
                      # function
                    list_s[i] = list_s[j]
                    combinations(''.join(list_s),j,n)
                    list_s[i] = '$'
                 
             
         
     
 
 
if __name__ == '__main__':
    s = "23$$"
    combinations(s,0,len(s))
    for x in possible_comb:
        print(x)


Javascript




<script>
// stores all possible non-repetitive combinations
// of string by replacing ‘$’ with any
// other digit from the string
let possible_comb = new Set();
function combinations(s, i, n)
{
 
    if(i==n)
        return;
    // to check whether a string is
    // valid combination
    let is_combination = true;
    for(let i = 0; i < s.length; i++)
    {
        if(s[i] == '$')
        {
            is_combination = false;
            break;
        }
    }
     
    if(is_combination && possible_comb.has(s)==false)
    {
        possible_comb.add(s);
        return;
    }
     
    for(let i = 0; i < n; i++)
    {
        if(s[i] == '$')
        {
            for(let j = 0; j < n; j++)
            {
                if(s[j] != '$')
                {
                    // replace the character having '$'
                    // with one of the digit from the
                    // string and recur in the combination
                    // function
                    let c = s[j];
                    s = s.substring(0,i) + c + s.substring(i+1)
                    combinations(s, j, n);
                    s = s.substring(0,i) + '$' + s.substring(i+1)
                }
            }
        }
    }
}
 
// driver code
let s;
s = "23$$";
let len = s.length;
combinations(s, 0, len);
 
for(let x of possible_comb)
{
    document.write(x,"</br>");
}
 
// This code is contributed by shinjanpatra.
</script>


C#




using System;
using System.Collections.Generic;
 
public class GFG
{
    // stores all possible non-repetitive combinations
    // of string by replacing ‘$’ with any
    // other digit from the string
    static HashSet<string> possible_comb = new HashSet<string>();
 
    static void Combinations(string s, int k, int n)
    {
        if (k == n)
        {
            return;
        }
 
        // to check whether a string is
        // valid combination
        bool is_combination = true;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '$')
            {
                is_combination = false;
                break;
            }
        }
 
        if (is_combination && !possible_comb.Contains(s))
        {
            possible_comb.Add(s);
            return;
        }
 
        for (int i = 0; i < n; i++)
        {
            if (s[i] == '$')
            {
                for (int j = 0; j < n; j++)
                {
                    if (s[j] != '$')
                    {
                        // replace the character having '$'
                        // with one of the digit from the
                        // string and recur in the combination
                        // function
                        s = s.Substring(0, i) + s[j] + s.Substring(i + 1);
                        Combinations(s, j, n);
                        s = s.Substring(0, i) + '$' + s.Substring(i + 1);
                    }
                }
            }
        }
    }
 
    // Driver Code
    public static void Main()
    {
        string s = "23$$";
        int len = s.Length;
        Combinations(s, 0, len);
        foreach (string x in possible_comb)
        {
            Console.WriteLine(x);
        }
    }
}


Output

2333
2332
2322
2323

Time Complexity:- O(n^x) where x is the number of instances of $ in the string and n is the length of string

Auxiliary Space:- O(1)



Last Updated : 09 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads