Problem

Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.

https://leetcode.com/problems/find-unique-binary-string/

Example 1:

Input: nums = ["01","10"]
Output: "11"
Explanation: "11" does not appear in nums. "00" would also be correct.

Example 2:

Input: nums = ["00","01"]
Output: "11"
Explanation: "11" does not appear in nums. "10" would also be correct.

Example 3:

Input: nums = ["111","011","001"]
Output: "101"
Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct.

Constraints:

  • n == nums.length
  • 1 <= n <= 16
  • nums[i].length == n
  • nums[i] is either '0' or '1'.
  • All the strings of nums are unique.

Test Cases

1
2
class Solution:
def findDifferentBinaryString(self, nums: List[str]) -> str:
solution_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import pytest

from solution import Solution


def verify(res: str, nums: list[str]):
assert res not in nums
assert len(res) == len(nums[0])
for d in res:
assert d in '01'


@pytest.mark.parametrize('nums, expected', [
(["01","10"], "11"),
(["00","01"], "11"),
(["111","011","001"], "101"),
])
@pytest.mark.parametrize('sol', [Solution()])
def test_solution(sol, nums, expected):
res = sol.findDifferentBinaryString(nums)
if res != expected:
verify(res, nums)

Thoughts

取 0 到 n(包含)的所有整数(共 n + 1 个),这些数字都可以表达成长度为 n 的二进制形式(左补零),且根据鸽笼原理,这 n + 1 个整数中,至少有一个不在 nums 中。

用一个集合记录 [0, n] 区间内所有整数,遍历 nums,对于 nums 中的每一个二进制串,转成整数后从集合中删除该数字。最后集合中至少会剩余一个数字。从集合剩余的数字中任取一个,格式化为长度为 n 的二进制字符串,返回即可。

时间复杂度 O(n²),空间复杂度 O(n)

Code

solution.py
1
2
3
4
5
6
7
8
class Solution:
def findDifferentBinaryString(self, nums: list[str]) -> str:
n = len(nums[0])
candidates = set(range(n + 1))
for num in nums:
candidates.discard(int(num, 2))

return format(candidates.pop(), f'0{n}b')