The Wayback Machine - https://web.archive.org/web/20240917134113/https://www.geeksforgeeks.org/generate-all-binary-strings-from-given-pattern/
Open In App

Generate all binary strings from given pattern

Last Updated : 20 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
45.76%
11.4K

Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by ‘0’ or ‘1’. 
Example : 

Input: str = “1??0?101”
Output: 
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

Recommended Practice

Method 1 (Using Recursion) 
We pass index of next character to the recursive function. If the current character is a wildcard character ‘?’, we replace it with ‘0’ or ‘1’ and do the same for all remaining characters. We print the string if we reach at its end. 

Algorithm:
Step 1: Initialize the string first with some wildcard characters in it.
Step 2: Check if index position is equals to the size of string, If it is return.
Step 3: If wildcard character is present at index location, replace it by 0 or 1 accordingly.
Step 4: Print the output

Below is the implementation of the above approach:

C++




// Recursive C++ program to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
#include <iostream>
using namespace std;
 
// Recursive function to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
void print(string str, int index)
{
    if (index == str.size())
    {
        cout << str << endl;
        return;
    }
 
    if (str[index] == '?')
    {
        // replace '?' by '0' and recurse
        str[index] = '0';
        print(str, index + 1);
 
        // replace '?' by '1' and recurse
        str[index] = '1';
        print(str, index + 1);
 
        // No need to backtrack as string is passed
        // by value to the function
    }
    else
        print(str, index + 1);
}
 
// Driver code to test above function
int main()
{
    string str = "1??0?101";
 
    print(str, 0);
 
    return 0;
}


Java




// Recursive Java program to generate all
// binary strings formed by replacing
// each wildcard character by 0 or 1
import java.util.*;
import java.lang.*;
import java.io.*;
 
class binStr
{  
    // Recursive function to generate all binary
    // strings formed by replacing each wildcard
    // character by 0 or 1
    public static void print(char str[], int index)
    {
        if (index == str.length)
        {
            System.out.println(str);
            return;
        }
 
        if (str[index] == '?')
        {
            // replace '?' by '0' and recurse
            str[index] = '0';
            print(str, index + 1);
             
            // replace '?' by '1' and recurse
            str[index] = '1';
            print(str, index + 1);
             
            // NOTE: Need to backtrack as string
            // is passed by reference to the
            // function
            str[index] = '?';
        }
        else
            print(str, index + 1);
    }
 
    // driver code
    public static void main (String[] args)
    {
        String input = "1??0?101";
        char[] str = input.toCharArray();
        print(str, 0);
    }
}
 
// This code is contributed by Chhavi


Python3




# Recursive Python program to generate all
# binary strings formed by replacing
# each wildcard character by 0 or 1
 
# Recursive function to generate all binary
# strings formed by replacing each wildcard
# character by 0 or 1
def _print(string, index):
    if index == len(string):
        print(''.join(string))
        return
 
    if string[index] == "?":
 
        # replace '?' by '0' and recurse
        string[index] = '0'
        _print(string, index + 1)
 
        # replace '?' by '1' and recurse
        string[index] = '1'
        _print(string, index + 1)
 
        # NOTE: Need to backtrack as string
        # is passed by reference to the
        # function
        string[index] = '?'
    else:
        _print(string, index + 1)
 
# Driver code
if __name__ == "__main__":
 
    string = "1??0?101"
    string = list(string)
    _print(string, 0)
 
    # This code is contributed by
    # sanjeev2552
 
# Note: function name _print is used because
# print is already a predefined function in Python


C#




// Recursive C# program to generate all
// binary strings formed by replacing
// each wildcard character by 0 or 1
using System;
 
class GFG
{
    // Recursive function to generate
    // all binary strings formed by
    // replacing each wildcard character
    // by 0 or 1
    public static void print(char []str,
                             int index)
    {
        if (index == str.Length)
        {
            Console.WriteLine(str);
            return;
        }
 
        if (str[index] == '?')
        {
            // replace '?' by
            // '0' and recurse
            str[index] = '0';
            print(str, index + 1);
             
            // replace '?' by
            // '1' and recurse
            str[index] = '1';
            print(str, index + 1);
             
            // NOTE: Need to backtrack
            // as string is passed by
            // reference to the function
            str[index] = '?';
        }
        else
            print(str, index + 1);
    }
 
    // Driver Code
    public static void Main ()
    {
        string input = "1??0?101";
        char []str = input.ToCharArray();
        print(str, 0);
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// Recursive PHP program to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
 
// Recursive function to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
function print1($str, $index)
{
    if ($index == strlen($str))
    {
        echo $str."\n";
        return;
    }
 
    if ($str[$index] == '?')
    {
        // replace '?' by '0' and recurse
        $str[$index] = '0';
        print1($str, $index + 1);
 
        // replace '?' by '1' and recurse
        $str[$index] = '1';
        print1($str, $index + 1);
 
        // No need to backtrack as string is passed
        // by value to the function
    }
    else
        print1($str, $index + 1);
}
 
// Driver code
 
    $str = "1??0?101";
 
    print1($str, 0);
 
     
// This code is contributed by chandan_jnu
?>


Javascript




<script>
 
      // Recursive JavaScript program to generate all
      // binary strings formed by replacing
      // each wildcard character by 0 or 1
       
      // Recursive function to generate
      // all binary strings formed by
      // replacing each wildcard character
      // by 0 or 1
      function print(str, index) {
        if (index === str.length) {
          document.write(str.join("") + "<br>");
          return;
        }
 
        if (str[index] === "?") {
          // replace '?' by
          // '0' and recurse
          str[index] = "0";
          print(str, index + 1);
 
          // replace '?' by
          // '1' and recurse
          str[index] = "1";
          print(str, index + 1);
 
          // NOTE: Need to backtrack
          // as string is passed by
          // reference to the function
          str[index] = "?";
        } else print(str, index + 1);
      }
 
      // Driver Code
 
      var input = "1??0?101";
      var str = input.split("");
      print(str, 0);
       
</script>


Output: 

10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

 

Time Complexity: O(2N), where N is the length of the given string and there are 2 possibilities.
Auxiliary Space: O(N2), as a copy of the string is created in every recursive call.

Method 2 (Using Queue) 
We can also achieve this by using iteration. The idea is to use queue, We find position of first occurrence of wildcard character in the input string and replace it by ‘0’ , then ‘1’ and push both strings into the queue. Then we pop next string from the queue, and repeat the process till queue is empty. If no wildcard characters are left, we simply print the string.
Iterative C++ implementation using queue. 
 

C++




// Iterative C++ program to generate all binary
// strings formed by replacing each wildcard
// character by 0 or 1
#include <iostream>
#include <queue>
using namespace std;
 
// Iterative function to generate all binary strings
// formed by replacing each wildcard character by 0
// or 1
void print(string str)
{
    queue<string> q;
    q.push(str);
 
    while (!q.empty())
    {
        string str = q.front();
 
        // find position of first occurrence of wildcard
        size_t index = str.find('?');
 
        // If no matches were found,
        // find returns string::npos
        if(index != string::npos)
        {
            // replace '?' by '0' and push string into queue
            str[index] = '0';
            q.push(str);
 
            // replace '?' by '1' and push string into queue
            str[index] = '1';
            q.push(str);
        }
 
        else
            // If no wildcard characters are left,
            // print the string.
            cout << str << endl;
 
        q.pop();
    }
}
 
// Driver code to test above function
int main()
{
    string str = "1??0?101";
 
    print(str);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
    // Iterative Java program to generate all binary
// strings formed by replacing each wildcard
// character by 0 or 1
 
// Iterative function to generate all binary strings
// formed by replacing each wildcard character by 0
// or 1
static void print(String str)
{
    Queue<String> q = new LinkedList<>();
    q.add(str);
 
    while (!q.isEmpty())
    {
        str = q.remove();
 
        // find position of first occurrence of wildcard
        int index = str.indexOf('?');
 
        // If no matches were found,
        // find returns string::npos
        if(index != -1)
        {
            // replace '?' by '0' and add string into queue
            str = str.substring(0,index) + '0' + str.substring(index+1);
            q.add(str);
 
            // replace '?' by '1' and add string into queue
            str = str.substring(0,index) + '1' + str.substring(index+1);
            q.add(str);
        }
 
        else
            // If no wildcard characters are left,
            // print the string.
            System.out.println(str);
 
    }
}
     
// Driver Code
public static void main(String args[])
{
    String str = "1??0?101";
    print(str);
 
}
}
 
// This code is contributed by shinjanpatra


Python3




# Iterative Python program to generate all binary
# strings formed by replacing each wildcard
# character by 0 or 1
  
# Iterative function to generate all binary strings
# formed by replacing each wildcard character by 0
# or 1
def Print(Str):
    q = []
    q.append(Str)
    while(len(q) > 0):
        Str = q[0]
         
        # find position of first occurrence of wildcard
        try:
            index = Str.index('?')
        except ValueError:
            index = -1
             
        # If no matches were found,
        # find returns -1
        if(index != -1):
            
            # replace '?' by '0' and push string into queue
            s1=Str.replace('?','0',1)
            q.append(s1)
             
            # replace '?' by '1' and push string into queue
            s2=Str.replace('?','1',1)
            q.append(s2)
        else:
            # If no wildcard characters are left,
            # print the string.
            print(Str)
        q.pop(0)
             
# Driver code
Str = "1??0?101"
Print(Str)
 
# This code is contributed by Pushpesh Raj


C#




// C# program to implement the approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  // Iterative C# program to generate all binary
  // strings formed by replacing each wildcard
  // character by 0 or 1
 
  // Iterative function to generate all binary strings
  // formed by replacing each wildcard character by 0
  // or 1
  static void print(string Str)
  {
 
    var q = new List<string>();
    q.Add(Str);
    while (q.Count > 0) {
      Str = q[0];
 
      // find position of first occurrence of wildcard
      int index = Str.IndexOf('?');
 
      // If no matches were found,
      // find returns -1
      if (index != -1) {
 
        // replace '?' by '0' and push string into
        // queue
        Str = Str.Substring(0, index) + '0'
          + Str.Substring(index + 1);
        q.Add(Str);
 
        // replace '?' by '1' and push string into
        // queue
        Str = Str.Substring(0, index) + '1'
          + Str.Substring(index + 1);
        q.Add(Str);
      }
 
      else {
 
        // If no wildcard characters are left,
        // print the string.
        Console.WriteLine(Str);
      }
 
      q.RemoveAt(0);
    }
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    string str = "1??0?101";
     
    // Function call
    print(str);
  }
}
 
// This code is contributed by phasing17


Javascript




<script>
 
// Iterative JavaScript program to generate all binary
// strings formed by replacing each wildcard
// character by 0 or 1
 
// Iterative function to generate all binary strings
// formed by replacing each wildcard character by 0
// or 1
function Print(Str){
 
    let q = []
    q.push(Str)
 
    while (q.length > 0){
        let Str = q[0]
 
        // find position of first occurrence of wildcard
        let index = Str.indexOf('?')
     
        // If no matches were found,
        // find returns -1
        if(index != -1)
        {
         
            // replace '?' by '0' and push string into queue
            Str = Str.replace(Str[index] , '0')
            q.push(Str)
 
            // replace '?' by '1' and push string into queue
            Str = Str.replace(Str[index] , '1')
            q.push(Str)
        }
 
        else
        {
         
            // If no wildcard characters are left,
            // print the string.
            document.write(Str,"</br>")
        }
 
        q.shift()
    }
}
 
// Driver code to test above function
let Str = "1??0?101"
Print(Str)
 
// This code is contributed by shinjanpatra
 
</script>


Output: 

10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

 

Time Complexity: O(N*2N),  where N is the size of the string.
Auxiliary Space: O(2N)

Method 3 (Using str and Recursion) 
 

C++




// C++ program to implement the approach
#include <bits/stdc++.h>
 
using namespace std;
 
/* we store processed strings in all (array)
we see if string as "?", if so, replace it with 0 and 1
and send it back to recursive func until base case is
reached which is no wildcard left */
 
vector<string> res;
 
void genBin(string s)
{
    auto pos = s.find('?');
    if (pos != string::npos) {
        // copying s to s1
        string s1 = s;
        // replacing first occurrence of ?
        // with 0
        s1.replace(pos, 1, "0");
        // copying s to s2
        string s2 = s;
        // replacing first occurrence of ?
        // with 1
        s2.replace(pos, 1, "1");
        genBin(s1);
        genBin(s2);
    }
    else {
        res.push_back(s);
    }
}
 
// Driver code
int main()
{
    genBin("1??0?101");
    for (string x : res) {
        cout << x << " ";
    }
}
 
// This code is contributed by phasing17


Java




import java.io.*;
import java.util.*;
 
class GFG
{
 
  // we store processed strings in all (array)
  // we see if string as "?", if so, replace it with 0 and 1
  // and send it back to recursive func until base case is reached
  // which is no wildcard left
  static ArrayList<String>res = new ArrayList<String>();
  static void genBin(String s) {
    if (s.indexOf('?') != -1) {
      String s1 = s.replaceFirst("\\?", "0"); // only replace once
      String s2 = s.replaceFirst("\\?", "1"); // only replace once
      genBin(s1);
      genBin(s2);
    }
    else res.add(s);
  }
 
  public static void main(String[] args) {
    genBin("1??0?101");
    System.out.println(res);
  }
}


Python3




#we store processed strings in all (array)
#we see if string as "?", if so, replace it with 0 and 1
#and send it back to recursive func until base case is reached
#which is no wildcard left
 
res = []
def genBin(s):
    if '?' in s:
        s1 = s.replace('?','0',1) #only replace once
        s2 = s.replace('?','1',1) #only replace once
        genBin(s1)
        genBin(s2)
    else: res.append(s)
 
# Driver code
genBin("1??0?101")
print(res)
 
# This code is contributed by
# divay pandey


C#




// C# code to implement the approach
 
using System;
using System.Collections.Generic;
 
class GFG {
 
    // we store processed strings in all (array)
    // we see if string as "?", if so, replace it with 0 and
    // 1 and send it back to recursive func until base case
    // is reached which is no wildcard left
    static List<string> res = new List<string>();
    static void genBin(string s)
    {
        int ind = s.IndexOf("?");
        if (ind != -1) {
            string s1 = s.Remove(ind, 1).Insert(
                ind, "0"); // only replace once
            string s2 = s.Remove(ind, 1).Insert(
                ind, "1"); // only replace once
            genBin(s1);
            genBin(s2);
        }
        else
            res.Add(s);
    }
     
   
      // Driver code
    public static void Main(string[] args)
    {
        genBin("1??0?101");
        foreach(var ele in res) Console.Write(ele + " ");
    }
}
 
 
// This code is contributed by phasing17


Javascript




<script>
/* we store processed strings in all (array)
we see if string as "?", if so, replace it with 0 and 1
and send it back to recursive func until base case is reached
which is no wildcard left */
  
let res = []
function genBin(s){
  if(s.includes('?')){
    let s1 = s.replace(/\?/,'0') //only replace once
    let s2 = s.replace(/\?/,'1') //only replace once
    genBin(s1)
    genBin(s2)
  }else{
    res.push(s)
  }
}
  
// Driver code
genBin("1??0?101")
document.write(res)
  
// This code is contributed by
// Santanu Panda
</script>


Output: 

['10000101', '10001101', '10100101', '10101101', '11000101', '11001101', '11100101', '11101101']

 

Time Complexity: O(N*2N),  where N is the size of the string.
Auxiliary Space: O(2N)



Previous Article
Next Article

Similar Reads

Generate all Binary Strings of length N with equal count of 0s and 1s
Given an integer N, the task is to generate all the binary strings with equal 0s and 1s. If no strings are possible, print -1 Examples: Input: N = 2 Output: “01”, “10”Explanation: All possible binary strings of length 2 are: 01, 10, 11, 00. Out of these, only 2 have equal number of 0s and 1s Input: 4 Output: “0011”, “0101”, “0110”, “1100”, “1010”,
6 min read
Generate all the binary strings of N bits
Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.Examples: Input: 2Output:0 00 11 01 1Input: 3Output:0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: The idea is to try
8 min read
Generate all binary strings without consecutive 1's
Given an integer, K. Generate all binary strings of size k without consecutive 1's. Examples: Input : K = 3 Output : 000 , 001 , 010 , 100 , 101 Input : K = 4 Output :0000 0001 0010 0100 0101 1000 1001 1010Idea behind that is IF string ends with '1' then we put only '0' at the end. IF string ends with '0' then we put both '0' and '1' at the end of
15 min read
Search strings with the help of given pattern in an Array of strings
Prerequisite: Trie | (Insert and Search) Given an array of strings words[] and a partial string str, the task is to find the strings of the given form str from the given array of string. A partial string is a string with some missing characters. For Example: "..ta", is a string of length 4 ending with "ta" and having two missing character at index
12 min read
Generate all possible strings formed by replacing letters with given respective symbols
Given a string S consisting of N characters and an array M[] of pairs of characters such that any character M[i][0] can be replaced with the character M[i][1] in the string S, the task is to generate all the possible strings formed by replacing some characters of the string with their respective symbols in the array M[]. Examples: Input: S = "aBc”,
5 min read
Generate a string which differs by only a single character from all given strings
Given an array of strings str[] of length N, consisting of strings of the same length, the task is to find the string which only differs by a single character from all the given strings. If no such string can be generated, print -1. In case of multiple possible answers, print any of them. Example: Input: str[] = { "abac", "zdac", "bdac"} Output: ad
15 min read
Generate a String from given Strings P and Q based on the given conditions
Given two strings P and Q, the task is to generate a string S satisfying the following conditions: Find S such that P is rearranged and Q is a substring in it.All the characters before Q in S should be smaller than or equal to the first character in Q and in lexicographic order.The rest of the characters should be present after Q in lexicographic o
7 min read
Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Generate Binary Strings of length N using Branch and Bound
The task is to generate a binary string of length N using branch and bound technique Examples: Input: N = 3 Output: 000 001 010 011 100 101 110 111 Explanation: Numbers with 3 binary digits are 0, 1, 2, 3, 4, 5, 6, 7 Input: N = 2 Output: 00 01 10 11 Approach: Generate Combinations using Branch and Bound : It starts with an empty solution vector.Whi
6 min read
Find the occurrence of the given binary pattern in the binary representation of the array elements
Given an array arr[] of N positive integers and a string patt which consists of characters from the set {0, 1}, the task is to find the count occurrence of patt in the binary representation of every integer from the given array. Examples: Input: arr[] = {5, 106, 7, 8}, patt = "10" Output: 1 3 0 1 binary(5) = 101 -&gt; occurrence(10) = 1 binary(106)
9 min read
Print all Strings from array A[] having all strings from array B[] as subsequence
Given two arrays A[] and B[] consisting of strings, the task is to print the strings from array A[] having all strings in B[] as a subsequence.Examples: Input: A[] = {"geeksforgeeks", "mapple", "twitter", "table", "Linkedin"}, B[] = {"e", "l"} Output: mapple table linkedin Explanation: Both the strings "e" and "l" are subsets in "mapple", "table",
11 min read
Find the string among given strings represented using given encryption pattern
Given an array of strings arr[] of size N and an encrypted string str, the task is to find the correct string from the given array of strings whose encryption will give str where str is encrypted using the following rules: The starting characters form an integer representing the number of uppercase symbols In the decrypted string.The next 3 charact
8 min read
Generate all possible strings such that char at index i is either str1[i] or str2[i]
Given two strings str1 and str2 each of length N, the task is to generate and print all possible strings of length N such that the character at index i of the generated string is either str1[i] or str2[i]Examples: Input: str1 = "abc", str2 = "def" Output: abc abf aec aef dbc dbf dec defInput: str1 = "a", str2 = "b" Output: a b Approach: The problem
5 min read
Find all Palindrome Strings in given Array of strings
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "racecar"Explanation: These two are the only palindro
6 min read
Find all strings that match specific pattern in a dictionary
Given a dictionary of words, find all strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary. Examples: Input: dict = ["abb", "abc", "xyz", "xyy"]; pattern = "foo" Output: [xyy abb] xyy and abb have same character at index 1 and 2 like the pattern Input: dict = ["abb", "abc", "x
15+ min read
Generate all the binary number from 0 to n
Given a positive integer number n generate all the binary number from 0 to n. Examples: Input : 5 Output : 0 1 10 11 100 101 Binary numbers are 0(0), 1(1), 2(10), 3(11), 4(100) and 5(101). Input : 10 Output : 0 1 10 11 100 101 110 111 1000 1001 1010 This program simple use predefined function (itoa() in C++) which convert in which base you want. so
6 min read
Generate all binary numbers in range [L, R] with same length
Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. The length of all binary numbers should be same. Examples: Input: L = 2, R = 4Output:010011100Explanation: The binary representation of the numbers: 2 = 10, 3 = 11 and 4 = 100.For the numbers to have same length one preceding 0 is added
6 min read
Minimize flips on adjacent 2 to 3 bits to generate a binary string of all 1s
Given a binary string S consisting of 0's and 1's, The task is to find the minimum number of flips required to generate a binary string of all ones. The flip is performed on either two or three adjacent indices. Examples: Input: S = "0010"Output: 2Explanation: Operations performed are: 0010 -&gt; 0001 -&gt; 1111 Input: S = "0011110"Output: 3Explana
7 min read
Queries to count distinct Binary Strings of all lengths from N to M satisfying given properties
Given a K and a matrix Q[][] consisting of queries of the form {N, M}, the task for each query is to count the number of strings possible of all lengths from Q[i][0] to Q[i][1] satisfying the following properties: The frequency of 0's is equal to a multiple of K.Two strings are said to be different only if the frequencies of 0's and 1's are differe
6 min read
Flip all 0s in given Binary Strings K times with different neighbours
Given a binary string S of size N and a positive integer K, the task is to repeatedly modify the given string K number of times by flipping all the 0s having different adjacent characters in each iteration. Note: For the character 0 present at 0th index then it will change to 1 only when 1st index character is 1 and if the last index character is 0
8 min read
Count strings that end with the given pattern
Given a pattern pat and a string array sArr[], the task is to count the number of strings from the array that ends with the given pattern. Examples: Input: pat = "ks", sArr[] = {"geeks", "geeksforgeeks", "games", "unit"} Output: 2 Only string "geeks" and "geeksforgeeks" end with the pattern "ks". Input: pat = "abc", sArr[] = {"abcd", "abcc", "aaa",
7 min read
Print all strings of maximum length from an array of strings
Given an array of strings arr[], the task is to print all the strings of maximum length from the given array. Example: Input: arr[] = {“aba”, “aa”, “ad”, “vcd”, “aba”}Output: aba vcd abaExplanation:Maximum length among all the strings from the given array is 3.The strings having length equal to 3 from the array are “aba”, “vcd”, “aba”. Input: arr[]
7 min read
Append digits to the end of duplicate strings to make all strings in an array unique
Given an array arr[] consisting of N strings, the task is to modify the array by replacing the duplicate strings by appending any number such that all the strings in the array are unique. Examples: Input: S = {"aa", "bb", "cc", "bb", "aa", "aa", "aa"}Output: {"aa", "bb", "cc", "bb1", "aa1", "aa2", "aa3"}Explanation:The output of the second occurren
5 min read
Make all Strings palindrome by swapping characters from adjacent Strings
Given an array of strings S[] of size X where each string has length N. In one move, you can swap the ith character of two adjacent strings, the task is to find the minimum number of moves to make every string a palindrome. If this is not possible, print -1. Examples: Input: S[] = {"13", "21", "32"}Output: 2?Explanation: We make all the strings pal
10 min read
Maximize sum by splitting given binary strings based on given conditions
Given two binary strings str1 and str2 each of length N, the task is to split the strings in such a way that the sum is maximum with given conditions. Split both strings at the same position into equal length substrings.If both the substrings have only 0's then the value of that substring to be added is 1.If both the substrings have only 1's then t
7 min read
Maximize given function by selecting equal length substrings from given Binary Strings
Given two binary strings s1 and s2. The task is to choose substring from s1 and s2 say sub1 and sub2 of equal length such that it maximizes the function: fun(s1, s2) = len(sub1) / (2xor(sub1, sub2)) Examples: Input: s1= "1101", s2= "1110"Output: 3Explanation: Below are the substrings chosen from s1 and s2Substring chosen from s1 -&gt; "110"Substrin
11 min read
Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
Generate string with Hamming Distance as half of the hamming distance between strings A and B
Given two Binary string A and B of length N, the task is to find the Binary string whose Hamming Distance to strings A and B is half the Hamming Distance of A and B.Examples: Input: A = "1001010", B = "0101010" Output: 0001010 Explanation: The hamming distance of the string A and B is 2. The hamming distance of the output string to A is 1. The hamm
7 min read
Generate two output strings depending upon occurrence of character in input string.
Given an input string str[], generate two output strings. One of which consists of those character which occurs only once in input string and second which consists of multi-time occurring characters. Output strings must be sorted.Examples: Input : str[] = "geeksforgeeks"Output : String with characters occurring once:forString with characters occurr
7 min read
Generate an N-length array having GCD of all its pairs present in a given 2D array
Given a 2D array arr[][] consisting of N*N positive integers, the task is to generate an N-length array such that Greatest Common Divisors(GCD) of all possible pairs of that array is present in the array arr[][]. Examples: Input: N = 4, arr[] = {2, 1, 2, 3, 4, 3, 2, 6, 1, 1, 2, 2, 1, 2, 3, 2}Output: 4, 3, 6, 2Explanation:Considering the array A[] a
8 min read
Article Tags :
Practice Tags :