1980. Find Unique Binary String #1338
-
Topics: Given an array of strings Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find a binary string of length ApproachThe key idea is to construct a binary string where each bit is chosen such that it differs from the corresponding bit in each of the strings in Let's implement this solution in PHP: 1980. Find Unique Binary String <?php
/**
* @param String[] $nums
* @return String
*/
function findDifferentBinaryString($nums) {
$n = count($nums);
$result = '';
for ($i = 0; $i < $n; $i++) {
$s = $nums[$i];
$c = $s[$i];
$result .= ($c === '0' ? '1' : '0');
}
return $result;
}
// Test cases
$nums1 = ["01", "10"];
echo findDifferentBinaryString($nums1) . "\n";
$nums2 = ["00", "01"];
echo findDifferentBinaryString($nums2) . "\n";
$nums3 = ["111", "011", "001"];
echo findDifferentBinaryString($nums3) . "\n";
?> Explanation:
This approach efficiently constructs the required string in O(n) time complexity, where |
Beta Was this translation helpful? Give feedback.
We need to find a binary string of length
n
that does not appear in the given arraynums
. The solution leverages a clever approach based on Cantor's diagonal argument to efficiently construct such a string.Approach
The key idea is to construct a binary string where each bit is chosen such that it differs from the corresponding bit in each of the strings in
nums
at a specific position. Specifically, for the i-th position of the resulting string, we take the i-th bit of the i-th string innums
and flip it (0 becomes 1 and 1 becomes 0). This ensures that the resulting string will differ from every string innums
in at least one position, guaranteeing that it is not present in the array.Let…