Find Unique Binary String — LeetCode 1980 Python Solution

MediumArrayHash TableStringBacktracking
Problem
#1980
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def findDifferentBinaryString(self, nums: List[str]) -> str:
        mask = 0
        for x in nums:
            mask |= 1 << x.count("1")
        n = len(nums)
        for i in range(n + 1):
            if mask >> i & 1 ^ 1:
                return "1" * i + "0" * (n - i)

Complexity

MeasureComplexity
TimeO(L), where L is the total length of the strings in `nums`
SpaceO(1) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1980. Find Unique Binary String is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1980. Find Unique Binary String?
LeetCode 1980. Find Unique Binary String is rated Medium on LeetCode.
What is the time complexity of LeetCode 1980. Find Unique Binary String?
The Python solution on this page runs in O(L), where L is the total length of the strings in `nums`.
What is the space complexity of LeetCode 1980. Find Unique Binary String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1980. Find Unique Binary String cover?
LeetCode 1980. Find Unique Binary String is tagged Array, Hash Table, String and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview