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.

Input & Output

Example 1 — Basic Case
$ Input: nums = ["01","10"]
Output: "00"
💡 Note: Using diagonal approach: flip bits at positions [0,1] from strings ["01","10"] → flip '0' to '1' and '1' to '0' → "10". Or we can return "00" or "11" as they're not in the input.
Example 2 — Single Element
$ Input: nums = ["0"]
Output: "1"
💡 Note: Only one string "0" exists, so we return the other possible string "1".
Example 3 — Three Strings
$ Input: nums = ["111","011","001"]
Output: "101"
💡 Note: Using diagonal: flip bits at positions [0,1,2] from ["111","011","001"] → flip '1','1','1' → "000". Any missing string like "101" is valid.

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

Visualization

Tap to expand
Find Unique Binary String Using Cantor's Diagonal Argument INPUT Array of n binary strings (each length n) nums = ["01", "10"] Index Matrix i=0: i=1: 0 1 1 0 Red = Diagonal elements nums[i][i] for each i Input Values: n = 2 nums = ["01", "10"] ALGORITHM STEPS 1 Initialize Result Start with empty string 2 Loop i = 0 to n-1 Process each diagonal 3 Flip Diagonal Bit If nums[i][i]='0' add '1' If nums[i][i]='1' add '0' 4 Return Result Guaranteed unique! Execution Trace: i=0: nums[0][0]='0' --> flip to '1' i=1: nums[1][1]='0' --> flip to '1' Result built: "" --> "1" --> "11" FINAL RESULT Unique Binary String Found "11" or "00" also valid Verification: "11" differs from "01" at i=0 OK "11" differs from "10" at i=1 OK Guaranteed different from every input string! Other Valid Answers: "00" or "11" (Both not in input array) Key Insight: Cantor's Diagonal Argument By flipping each diagonal element nums[i][i], the result string differs from nums[i] at position i. This guarantees the result is different from ALL strings in the input array. Time: O(n), Space: O(n). This elegant proof technique was invented by Georg Cantor to prove uncountability of real numbers. TutorialsPoint - Find Unique Binary String | Cantor's Diagonal Argument
Asked in
Google 12 Facebook 8 Amazon 6
32.1K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen