#1980

Find Unique Binary String

Medium
ArrayHash TableStringBacktrackingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a clever technique called the 'diagonal argument'. By constructing a binary string based on the existing strings, we can ensure that the new string is unique without generating all possibilities.

⚙️

Algorithm

2 steps
  1. 1Step 1: Create a new binary string where the i-th bit is the opposite of the i-th bit of the i-th string in nums.
  2. 2Step 2: Return this newly constructed string as it cannot be in the original list.
solution.py6 lines
1# Full working Python code
2
3def findUniqueBinaryString(nums):
4    n = len(nums)
5    unique_string = ''.join('1' if nums[i][i] == '0' else '0' for i in range(n))
6    return unique_string

Complexity note: The time complexity is O(n) because we iterate through the list once to construct the unique string. The space complexity is O(1) since we are using a fixed amount of space regardless of n.

  • 1Using the diagonal argument allows for guaranteed uniqueness without generating all combinations.
  • 2The brute force method is simple but inefficient for larger inputs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.