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 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'.nums are unique.This approach builds a unique binary string by considering each string's diagonal to ensure uniqueness. Specifically, we take advantage of the fact that flipping a bit diagonally guarantees that it differs from the original set of strings across at least one position. For each string at index i, we flip the character at the same index i, ensuring that the constructed string cannot match any existing strings due to its diagonal differentiation.
The Python solution generates a binary string by iterating over each index i of the strings in nums. At each index, it checks the diagonal bit nums[i][i] and inverts it. This results in a binary string that is guaranteed to be different from any given string in nums due to the difference along the diagonal.
Java
Time Complexity: O(n) since we iterate through the array once.
Space Complexity: O(n) for storing the resulting binary string of length n.
This approach uses backtracking to generate all possible binary strings of length n and checks for the first one not present in nums. While not as efficient as diagonal construction, this method demonstrates a different strategy to ensure a solution's validity by exhaustive search.
The C# solution employs a backtracking method to explore every binary string possibility. If a binary string of the required length isn't in nums, it is identified as the result. The use of a recursive helper function facilitates generating possible candidates one bit at a time.
JavaScript
Time Complexity: O(2^n) due to generating every binary string of length n.
Space Complexity: O(n) for the call stack during recursion.
| Approach | Complexity |
|---|---|
| Diagonal Construction Approach | Time Complexity: |
| Backtracking Approach | Time Complexity: |
Find Unique Binary String - Leetcode Weekly Contest 1980 - Python • NeetCode • 17,894 views views
Watch 9 more video solutions →Practice Find Unique Binary String with our built-in code editor and test cases.
Practice on FleetCode