Generate all binary strings of length n with k bits set
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Generating all binary strings of length `n` with `k` bits set is a classic problem in combinatorics and computer science. This problem is useful in various domains such as algorithms design, data structures, and optimization problems. The challenge is to determine all possible ways to arrange `k` ones (`1`) and `n-k` zeros (`0`) in a binary string of length `n`.
Problem Statement
Given two non-negative integers, `n` and `k`, where `0 ≤ k ≤ n`, the task is to generate all binary strings of length `n` that contain exactly `k` bits set to 1. The generated strings must have exactly `k` ones and `n-k` zeros.
Technical Explanation
In mathematical terms, the task is to compute the combinations of placing `k` ones in `n` positions. This can be expressed using the binomial coefficient:
This formula gives the number of ways to choose `k` positions from `n` available positions to place ones, while the rest will naturally be zeros.
Example
Consider `n = 4` and `k = 2`. The task is to generate all binary strings of length 4 with exactly 2 ones. Using the combination formula, there are possible combinations:
• 1100 • 1010 • 1001 • 0110 • 0101 • 0011
These strings represent all possible ways to arrange 2 ones within a 4-bit binary number.
Algorithm
A recursive backtracking approach or iterative approach with bit manipulation is often employed to generate such patterns.
Recursive Approach
- Base Case: If the length of the string is `n` and the count of ones is `k`, then print or store the string.
- Recursive Step: • If the count of ones added is less than `k`, append `1` and recursively call for the next position. • If the remaining positions `n-length` can accommodate the remaining ones `k-ones`, append `0` and recursively call for the next position.
Iterative Approach with Bit Manipulation
- Start from a binary string with the first `k` bits set to 1 and the rest set to zero.
- Generate permutations by treating each binary string as a bit pattern: • Identify the rightmost `1` that can still move to the right. • Move this `1` one position to the right and move all `1`s to its right as far left as possible.
- Repeat until all permutations are exhausted.
Implementation
Here's a Python implementation using the iterative bit manipulation technique:

