Find the First Near-Match Code With Optional Folding Rules
StringsAuto-graded · 23 test casesLast updated
Scan candidate codes in order and return the first whose normalized form is within a mismatch limit of a reference, using optional case folding and O/0, I/1 merging.
You are given a reference code and a list of candidate codes, all strings of letters and digits. Return the index of the first candidate that matches the reference under the rules below, or -1 if none does.
Normalization
Before any comparison, the reference and every candidate go through the same normalization, in this order:
- Case handling. If
case_sensitiveisTrue, letters are compared exactly as given. If it isFalse, every string is converted to lower case. - Lookalike merging. If
merge_lookalikesisTrue, thenoandObecome0, andiandIbecome1. This applies whatever the value ofcase_sensitive. No other characters change. In particular,landLare not merged with1.
Matching
After normalization, a candidate matches if both of these hold:
- It has the same length as the normalized reference. A candidate of a different length never matches.
- Its mismatch count is at most
max_mismatches. The mismatch count is the number of positions where the two strings have different characters.
With max_mismatches = 0, a match is an exact equality of the normalized strings.
Selection
Scan the candidates from left to right and return the index of the first one that matches. Do not look for the candidate with the smallest mismatch count. The earliest acceptable candidate wins, even if a later one is closer.
If max_mismatches is negative, nothing can match, so return -1. If there are no candidates, return -1.
Defaults
max_mismatches defaults to 0, case_sensitive defaults to True, and merge_lookalikes defaults to False.
Constraints
- Every string consists of ASCII letters and digits.
- Strings may have any length, including different lengths from the reference.
candidatesmay be empty.max_mismatchesis an integer and may be negative.- The return value is an integer index into
candidates, or-1.
Examples
Example 1
Input: first_close_code('A7K0P91', ['A7K0P91', 'A7K0P92', 'A7KOP91', 'a7k0p91'])
Output: 0
Example 2
Input: first_close_code('A7K0P91', ['x7k0p91', 'A7KOP91', 'A7K0P92', 'ZZZZZZZ'], 0, True, True)
Output: 1
Example 3
Input: first_close_code('A7K0P91', ['a7k0p92', 'A7K0P99', 'B7K0P91', 'A7K0P90'], 1, False, False)
Output: 0
Example 4
Input: first_close_code('O1A2B3C', ['01A2B3C', 'O1A2B3C', 'OIA2B3C', 'x'], 0, True, True)
Output: 0
Hints
Hint 1
Write one helper that applies the normalization steps to a string, and run it on the reference and on every candidate.
Hint 2
Skip any candidate whose normalized length differs from the reference. Otherwise count the positions where the characters differ.
Hint 3
Return as soon as a candidate has a mismatch count within the limit. Do not keep searching for a closer one. Remember the negative-limit case.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Normalize first, then compare. Both the reference and each candidate go through the same normalization: lower-case them if the comparison is not case sensitive, then map o/O to 0 and i/I to 1 if lookalike merging is on.
Normalize the reference once. Then scan the candidates in order:
- Normalize the candidate.
- If its length differs from the reference's, skip it. Mismatch counting is only defined for equal-length strings.
- Count the positions where the characters differ.
- If the count is at most
max_mismatches, return the current index immediately.
If the loop ends without a match, return -1. A negative limit is handled up front by returning -1.
Why it is correct
- Applying identical normalization to both sides means the comparison sees only the differences the rules care about.
- Counting differing positions is exactly the mismatch count for equal-length strings. Requiring equal lengths rules out candidates that cannot be compared position by position.
- Returning at the first acceptable candidate follows the "earliest index wins" rule, so a later, closer candidate is never preferred.
- With
max_mismatches = 0, the test reduces to exact equality of the normalized strings. - With
case_sensitive=False,"a7k0p92"and"A7K0P91"both become lower case and differ in one position, so a limit of 1 accepts the first candidate.
Complexity
Let n be the number of candidates and L the longest string length. Time is O(n * L), because each candidate is normalized and compared once. Extra space is O(L) for the normalized strings.
Reference solution
from typing import List
def first_close_code(target_code, candidates, max_mismatches=0, case_sensitive=True, merge_lookalikes=False):
if max_mismatches < 0:
return -1
table = str.maketrans({
'o': '0', 'O': '0',
'i': '1', 'I': '1',
})
def normalize(s):
if not case_sensitive:
s = s.lower()
if merge_lookalikes:
s = s.translate(table)
return s
target = normalize(target_code)
for index, candidate in enumerate(candidates):
value = normalize(candidate)
if len(value) != len(target):
continue
mismatches = sum(a != b for a, b in zip(target, value))
if mismatches <= max_mismatches:
return index
return -1