Codepath

Performer Schedule Pattern

Unit 2 Session 1 (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the problem asking for?

    • A: The problem asks to determine if a given schedule string follows the same pattern as defined by the pattern string. Each character in pattern should map to a non-empty word in schedule with a one-to-one correspondence.
  • Q: What are the inputs?

    • A: Two strings, pattern and schedule.
  • Q: What are the outputs?

    • A: A boolean value, True if the schedule follows the pattern, and False otherwise.
  • Q: Are there any constraints on the strings?

    • A: Each character in pattern should map to a unique word in schedule and vice versa.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

For this problem, we can begin by reading through the given code and translating the code into plain English to ensure we understand how the code is working.

General Idea: Use two dictionaries to establish a bidirectional mapping between characters in pattern and words in schedule.

1. Split `schedule` into words and store in `genres`.
2. Check if the length of `genres` matches the length of `pattern`. If not, return `False`.
3. Initialize two dictionaries: `char_to_genre` and `genre_to_char`.
4. Iterate over characters in `pattern` and corresponding words in `genres`.
   - If the character is already in `char_to_genre`, check if it maps to the same word. If not, return `False`.
   - If the word is already in `genre_to_char`, check if it maps to the same character. If not, return `False`.
   - Otherwise, add the new mapping to both dictionaries.
5. If all checks pass, return `True`.

Once we understand the existing code, add function calls using happy and edge cases to find example input where the current code does not match the expected output.

Then, we can add print() statements and use the Stack Trace to debug.

I-mplement

def schedule_pattern(pattern, schedule):
    genres = schedule.split()

    # Fix the length check
    if len(genres) != len(pattern):
        return False

    char_to_genre = {}
    genre_to_char = {}

    for char, genre in zip(pattern, genres):
        if char in char_to_genre:
            if char_to_genre[char] != genre:
                return False
        else:
            char_to_genre[char] = genre

        if genre in genre_to_char:
            if genre_to_char[genre] != char:
                return False
        else:
            genre_to_char[genre] = char

    return True
Fork me on GitHub