VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-a-random-binary-string-of-length-n/

⇱ Generate a random Binary String of length N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate a random Binary String of length N

Last Updated : 23 Jul, 2025

Given a positive integer N, the task is to generate a random binary string of length N.

Examples:

Input: N = 7
Output: 1000001

Input: N = 5
Output: 01001

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:

Below is the implementation of the above approach:


Output: 
0101101

 

Time Complexity: O(N) In the above-given approach, there is one loop for iterating over string which takes O(N) time in worst case. Therefore, the time complexity for this approach will be O(N).
Auxiliary Space: O(N)// an extra variable store all the characters of the string and in worst case all characters will be unique hence algorithm takes up linear space

Comment
Article Tags: