DEV Community

Dolly Sharma
Dolly Sharma

Posted on

1980-find Unique String (Day-08)

Interview Trick: Find a Binary String Not Present in the Array

One interesting interview problem asks:

Problem

You are given n unique binary strings of length n.
Return any binary string of length n that does not appear in the array.

Example:

Input:
nums = ["01","10"]

Output:
"11"   // or "00"
Enter fullscreen mode Exit fullscreen mode

Brute Force Idea

Since each string has length n, there are:

2^n
Enter fullscreen mode Exit fullscreen mode

possible binary strings.

If we generate all 2^n strings and check which one is missing from the array, we can solve the problem.

However, this approach is inefficient.

Time Complexity

O(2^n * n)
Enter fullscreen mode Exit fullscreen mode

Optimal Interview Trick (Diagonal Method)

A much smarter approach uses a concept similar to Cantor’s Diagonalization.

Idea:

Construct a new string by flipping the diagonal bit of each string.

ans[i] = flip(nums[i][i])
Enter fullscreen mode Exit fullscreen mode

Where:

0 → 1
1 → 0
Enter fullscreen mode Exit fullscreen mode

Why This Works

For every index i:

ans[i] ≠ nums[i][i]
Enter fullscreen mode Exit fullscreen mode

That means the constructed string differs from the i-th string at position i.

Therefore:

  • ans ≠ nums[0]
  • ans ≠ nums[1]
  • ...
  • ans ≠ nums[n-1]

So the new string cannot exist in the array.


Example

nums = ["010",
        "111",
        "000"]
Enter fullscreen mode Exit fullscreen mode

Diagonal bits:

0 1 0
Enter fullscreen mode Exit fullscreen mode

Flip them:

1 0 1
Enter fullscreen mode Exit fullscreen mode

Result:

"101"
Enter fullscreen mode Exit fullscreen mode

This string differs from every string in nums.


C++ Implementation

class Solution {
public:
    string findDifferentBinaryString(vector<string>& nums) {
        int n = nums.size();
        string ans = "";

        for(int i = 0; i < n; i++) {
            if(nums[i][i] == '0')
                ans += '1';
            else
                ans += '0';
        }

        return ans;
    }
};
Enter fullscreen mode Exit fullscreen mode

Complexity

Time Complexity

O(n)
Enter fullscreen mode Exit fullscreen mode

Space Complexity

O(n)
Enter fullscreen mode Exit fullscreen mode

Key Interview Insight

Whenever you see:

  • n binary strings
  • each of length n
  • need a missing string

Think:

Flip the diagonal bits.

This guarantees a string different from every given string.

Top comments (0)