← 返回 tesla 的题目列表Bulls and Cows with Per-Position Match Signal
类型:qbank
Coding round on a Bulls-and-Cows / Guess-the-Word matching problem: given a target and a guess of equal length, emit a per-position signal marking exact matches, present-but-misplaced characters, and absent characters.
Requirements
Given a target string and a guess string of equal length, compare them character by character.
Emit a per-position result array rather than a single aggregate count.
For each position output one of three signals: exact match (right character, right position), present-elsewhere (character exists in the target but at another position), or absent (character not available).
A character in target can only be "used up" once when accounting for present-elsewhere matches, so once its occurrences are consumed it should report as absent.
Follow-up: solve it without a frequency counter / hashmap.
Examples
target = "sabby"
guess = "assby"
output = [1, 1, 0, 2, 2]
In this encoding 2 marks an exact position match, 1 marks present-elsewhere, and 0 marks absent.
Notes
This is the LeetCode 299 (Bulls and Cows) family, but the output shape differs: instead of returning "xAyB" bulls/cows totals, it returns a per-index signal.
Watch the character-exhaustion edge case: a naive per-position counter that does not decrement remaining availability will keep reporting present-elsewhere after the target's copies of that character are gone. A clean approach is two passes — first lock in exact matches, then consume remaining target characters from a multiset for the present-elsewhere checks.
For the no-counter follow-up, be ready to discuss alternatives such as sorting index pairs or bitmask tracking of consumed positions when the alphabet is small.
Interviewers here tend to pull problems ad hoc, so clarify the exact output contract (aggregate vs per-position, the meaning of each signal value) before coding.
Preparation
Implement the two-pass solution: pass one flags exact matches and decrements a target character count; pass two assigns present-elsewhere only while a count remains.
Test the character-exhaustion case (more copies in the guess than the target), all-exact, all-absent, and repeated-character inputs like the sabby / assby example.
Re-derive a counter-free variant so you can answer the follow-up under time pressure.