Find Unique Binary String

medium backtracking cantor diagonal

Problem

You are given an array nums of n distinct binary strings, each exactly n characters long. Return any binary string of length n that does not appear in nums. Since there are 2ⁿ possible strings and only n of them are taken, a missing string always exists; if several are missing, any one is accepted.

Inputnums = ["0110","1010","0010","1101"]
Output"1100"
Flipping each diagonal bit (0→1, 0→1, 1→0, 1→0) builds "1100", which differs from nums[i] at position i for every i — so it cannot be in the list.

def find_different_binary_string(nums):
    n = len(nums)
    ans = []
    for i in range(n):
        bit = nums[i][i]                        # diagonal bit
        ans.append('1' if bit == '0' else '0')  # flip it
    return ''.join(ans)
function findDifferentBinaryString(nums) {
  const n = nums.length;
  let ans = "";
  for (let i = 0; i < n; i++) {
    const bit = nums[i][i];          // diagonal bit
    ans += bit === "0" ? "1" : "0";  // flip it
  }
  return ans;
}
String findDifferentBinaryString(String[] nums) {
    int n = nums.length;
    StringBuilder ans = new StringBuilder();
    for (int i = 0; i < n; i++) {
        char bit = nums[i].charAt(i);       // diagonal bit
        ans.append(bit == '0' ? '1' : '0'); // flip it
    }
    return ans.toString();
}
string findDifferentBinaryString(vector<string>& nums) {
    int n = nums.size();
    string ans;
    for (int i = 0; i < n; i++) {
        char bit = nums[i][i];           // diagonal bit
        ans += (bit == '0') ? '1' : '0'; // flip it
    }
    return ans;
}
Time: O(n) Space: O(n)