Open In App

Check whether a binary string can be formed by concatenating given N numbers sequentially

Last Updated : 07 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sequence of 'n' numbers (without leading zeros), the task is to find whether it is possible to create a binary string by concatenating these numbers sequentially. 
If possible, then print the binary string formed, otherwise print "-1".

Examples : 

Input: arr[] = {10, 11, 1, 0, 10} 
Output: 10111010 
All the numbers contain the digits '1' and '0' only. So it is possible to form a binary string by concatenating 
these numbers sequentially which is 10111010.

Input: arr[] = {1, 2, 11, 10} 
Output: -1 
One of the numbers contains the digit '2' which cannot be a part of any binary string. 
So, the output is -1.

Approach: The main observation is that we can only concatenate those numbers which contain the digits '1' and '0' only. Otherwise, it is impossible to form a binary string.

Below is the implementation of the above approach : 

C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

// Function that returns false if
// the number passed as argument contains
// digit(s) other than '0' or '1'
bool isBinary(int n)
{
    while (n != 0) {
        int temp = n % 10;
        if (temp != 0 && temp != 1) {
            return false;
        }
        n = n / 10;
    }
    return true;
}

//Function that checks whether the 
//binary string can be formed or not
void formBinaryStr(int n, int a[])
{
    bool flag = true;

    // Empty string for storing
    // the binary number
    string s = "";

    for (int i = 0; i < n; i++) {

        // check if a[i] can be a
        // part of the binary string
        if (isBinary(a[i]))

            // Conversion of int into string
            s += to_string(a[i]);
        else {

            // if a[i] can't be a part
            // then break the loop
            flag = false;
            break;
        }
    }

    // possible to create binary string
    if (flag)
        cout << s << "\n";

    // impossible to create binary string
    else
        cout << "-1\n";
}

// Driver code
int main()
{

    int a[] = { 10, 1, 0, 11, 10 };
    int N = sizeof(a) / sizeof(a[0]);

    formBinaryStr(N, a);

    return 0;
}
Java Python3 C# PHP JavaScript

Output
10101110

Complexity Analysis:

  • Time Complexity: O(N*log(MAX)), where N is the length of the array and MAX is the maximum number in the array
  • Auxiliary Complexity: O(M), where M is the length of the string

Next Article
Practice Tags :

Similar Reads