Generate a random Binary String of length N
Given a positive integer N, the task is to generate a random binary string of length N.
Input: N = 7
Input: N = 5
Approach: The given problem can be solved by using the rand() function that generates a random number over the range [0, RAND_MAX] and with the help of the value returned by this function, any number in any range [L, R] can be generated as (rand() % (R – L + 1)) + L. Follow the steps below to solve the problem:
- Initialize an empty string, say S.
- Iterate over the range [0, N – 1] and perform the following steps:
- After completing the above steps, print the string S as the resulting binary string.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.