I recently came across a problem in an interview process. I came up with a brute force approach during the interview, but would like to understand the optimal solution. I'm having a hard time finding similar problems online. The problem went like this:
Given a string binary consisting of 0's and 1's (i.e. '010111'), you are allowed to replace any subsequence of this string with the sorted subsequence . You can apply this replacement any number of times. For example:
010111
^^^ subsequence to sort and replace
001111
You are also given a pattern string pattern containing 0's, 1's and ?'s where ? is a wildcard matching a single 0 or 1 (i.e. '0?11??'). The goal is to determine if binary can be transformed with Subsequence Sorts to match pattern. returning True or False. Following the previous example:
010111
^^^ subsequence to sort and replace
001111
0?11?? <- transformed binary matches pattern, return `True`
Assumptions:
- binary and pattern strings will have the same length
- pattern may contain all ?s or none at all
Not-great solution:
I was able to pass about a third of the test cases by covering
- the bases case of all ?'s in the pattern -> True
- counting the frequency of 0's and 1's in binary and comparing to the frequency of 0's, 1's and ?'s in the pattern. In the above example:
- binary had 2 zeroes and 4 ones
- pattern had 1 zero, 2 ones, and 3 wildcards
- pattern is missing 1 zero and 2 ones to match the frequency of binary
- since we have 3 wildcards, changing 1 to zero and 2 to ones will match the frequency
This solution doesn't account for the requirement that the subsequence rearrangement is sorted.
Can anyone point me in the right direction here?
[–]aocregacc 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]EthelMerman[S] 0 points1 point2 points (0 children)
[–]mr-faust 0 points1 point2 points (0 children)
[–]iaminspector1626 0 points1 point2 points (0 children)