Weighted 01 and 10 subsequence pairs with wildcards
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's online assessment, last asked Jan 2026. It tests strings, greedy and prefix sums.
A status string holds '0', '1' and '!'. After every '!' is replaced with '0' or '1', each pair of positions i < j that reads 0 then 1 adds x to the total, and each pair that reads 1 then 0 adds y. Pairs are subsequences: the two positions need not be next to each other. Choose the replacements that give the largest total and return it modulo 10^9 + 7. Trying every replacement is exponential.
Interface
Unless you agree on a different interface with the interviewer, assume:
max_weighted_pairs(s: str, x: int, y: int) -> int
Example
max_weighted_pairs("101!1", 3, 2) -> 15
# "!" = 0 gives "10101": three 01 pairs (3 each) and three 10 pairs (2 each) = 15
# "!" = 1 gives "10111": 11
max_weighted_pairs("0!!1", 2, 3) -> 9 # "0101"
max_weighted_pairs("!!!", 1, 1) -> 2 # for example "010"
max_weighted_pairs("!", 5, 7) -> 0 # one character has no pairs
Constraints
-
1 <= len(s) <= 10^5;1 <= x, y <= 10^9.
Clarifying questions
- Maximum or minimum? (Be ready for both.)
- Is the modulo applied only to the final answer? (Compare totals before reducing them.)
- Which weight goes with which order:
xfor01andyfor10?
What a strong answer covers
- Scanning left to right: a character's contribution depends only on how many
0s and1s come before it (and after it). - A DP over how many wildcards so far became
1works but is O(n²); the key fact is that an optimal answer sets the wildcards as one block of0s and one block of1s (all1s first or all0s first, depending on whetherxoryis larger), so trying each split point gives O(n) with prefix and suffix counts. - Exact big-number arithmetic (Python) or 128-bit intermediates before taking the modulo.
- A brute-force checker over small strings to test the fast version.
Follow-ups
- Return the minimum total instead: what changes in the block argument?
- Different weights per position.
- The string changes one character at a time: update the answer quickly.
Where it's asked
- Amazon · Online assessment · Last asked Jan 2026Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
