[Python][Coding Pattern] Find Missing Letter
Find Missing Letter
Purpose
A list of consecutive characters is given, and one letter is missing. The job is to find and return that missing letter.
Constraints
- The characters are guaranteed to be consecutive (e.g., a, b, c, d, f).
- The case (uppercase or lowercase) must be preserved.
- You can safely assume the missing character is not the last in the list.
- The list is at least two characters long.
Step-by-step Logic
Core Idea: Unicode Difference
Each alphabetical character has a corresponding Unicode value.
In a perfectly consecutive sequence (like `'a'` to `'z'` or `'A'` to `'Z'`), the **difference between any two adjacent letters is exactly 1**.
So, if any gap is larger than 1, that means a letter is missing.
1. Start a for loop with an index-based iteration using range(1, len(chars)).
This starts from the second element because we will be comparing each character with its previous one.
Starting from index 1 avoids accessing out-of-range indices like chars[-1].
2. Compare the Unicode values of each pair of adjacent characters using ord().
Specifically, subtract the Unicode value of the previous character from the current one:
ord(chars[i]) - ord(chars[i - 1]).
3. If the difference is not 1, it means there’s a missing character in between.
You can recover the missing character by subtracting 1 from the current character's Unicode:
chr(ord(chars[i]) - 1).
4. Return that character.
Key Python Methods Used
- ord(char) → Returns the Unicode integer of a character
- chr(code) → Converts a Unicode integer back into a character
- range() → Used for indexed iteration
- len() → Ensures we loop through the list safely
Comments
Post a Comment