All problems
0867MediumArrayTwo PointersStringGreedy

Matching a Pattern by Sorting a Subsequence

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3998Transform Binary String Using Subsequence Sort

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A tape reads s, a string of '0' and '1'. Each entry of strs is a pattern of the same length made of '0', '1' and '?', where '?' accepts either character.

One tidy picks any subsequence of positions of the tape and rewrites the characters at exactly those positions in non-decreasing order, leaving the rest of the tape untouched. Picking no positions is allowed.

For each pattern, decide whether one tidy can turn the tape into a string the pattern accepts. Return the positions in strs of the patterns for which it can, in increasing order.

Examples

Example 1

Input
s = "1010", strs = ["0011", "1010", "0101", "??0?"]
Output
[0, 1, 3]

Picking every position and sorting gives "0011", which the first pattern accepts. The second pattern already matches the tape, so picking nothing works. The fourth needs only a zero at position 2, which the tape already has.

Example 2

Input
s = "111", strs = ["000", "111", "??1"]
Output
[1, 2]

The tape holds no zero, so no tidy can produce one, and the first pattern is out of reach. The other two are already satisfied.

Example 3

Input
s = "0", strs = ["0", "1", "?"]
Output
[0, 2]

A tape of one character cannot be changed by sorting, so only the patterns that already accept it are reachable.

Constraints

  • 1 <= s.length <= 2000
  • 1 <= strs.length <= 2000
  • s[i] is either '0' or '1'
  • Every pattern in strs has the same length as s
  • strs[i][j] is '0', '1' or '?'

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def patterns_reachable(s: str, strs: list[str]) -> list[int]:
Java
public List<Integer> patternsReachable(String s, List<String> strs)
September 7
Apply