[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

# Problem:
# Given a list of consecutive (increasing) letters with one missing, return the missing letter.

# Example:
# find_missing_letter(['a','b','c','d','f']) -> 'e'

# Constraints:
# - The list will contain at least 2 letters
# - The letters will be either all uppercase or all lowercase
# - Only one letter will be missing

# Signature:
def find_missing_letter(chars: list[str]) -> str:
    # unicode, numbers, difference should be 1
    for i in range(1, len(chars)):
        if ord(chars[i]) - ord(chars[i-1]) != 1:
            return chr(ord(chars[i]) - 1)


if __name__ == '__main__':
    assert find_missing_letter(['a','b','c','d','f']) == 'e', 'test 1 failed'
    assert find_missing_letter(['O','Q','R','S']) == 'P', 'test 2 failed'
    assert find_missing_letter(['O','P', 'Q','S']) == 'R', 'test 3 failed'

Comments