Skip to content

1980. Find Unique Binary String 👍

Approach 1: Naive

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  string findDifferentBinaryString(vector<string>& nums) {
    const int bitSize = nums[0].length();
    const int maxNum = 1 << bitSize;
    unordered_set<int> numsSet;

    for (const string& num : nums)
      numsSet.insert(stoi(num, nullptr, 2));

    for (int num = 0; num < maxNum; ++num)
      if (!numsSet.contains(num))
        return std::bitset<16>(num).to_string().substr(16 - bitSize);

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public String findDifferentBinaryString(String[] nums) {
    final int bitSize = nums[0].length();
    final int maxNum = 1 << bitSize;
    Set<Integer> numsSet = Arrays.stream(nums)
                               .mapToInt(num -> Integer.parseInt(num, 2))
                               .boxed()
                               .collect(Collectors.toSet());

    for (int num = 0; num < maxNum; ++num)
      if (!numsSet.contains(num))
        return String.format("%" + bitSize + "s", Integer.toBinaryString(num)).replace(' ', '0');

    throw new IllegalArgumentException();
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def findDifferentBinaryString(self, nums: list[str]) -> str:
    bitSize = len(nums[0])
    maxNum = 1 << bitSize
    numsSet = {int(num, 2) for num in nums}

    for num in range(maxNum):
      if num not in numsSet:
        return f'{num:0>{bitSize}b}'

Approach 2: Heuristic

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  string findDifferentBinaryString(vector<string>& nums) {
    string ans;

    // Flip the i-th bit for each nums[i] so that `ans` is unique.
    for (int i = 0; i < nums.size(); ++i)
      ans += nums[i][i] == '0' ? '1' : '0';

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public String findDifferentBinaryString(String[] nums) {
    StringBuilder sb = new StringBuilder();

    // Flip the i-th bit for each nums[i] so that `ans` is unique.
    for (int i = 0; i < nums.length; ++i)
      sb.append(nums[i].charAt(i) == '0' ? '1' : '0');

    return sb.toString();
  }
}
1
2
3
class Solution:
  def findDifferentBinaryString(self, nums: list[str]) -> str:
    return ''.join('1' if num[i] == '0' else '0' for i, num in enumerate(nums))