1980. Find Unique Binary String
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.length1 <= n <= 16nums[i].length == nnums[i]is either'0'or'1'.- All the strings of
numsare unique.
Test Cases
class Solution:
def findDifferentBinaryString(self, nums: List[str]) -> str: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
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')
评论需要 JavaScript。