-
Notifications
You must be signed in to change notification settings - Fork 266
Performer Schedule Pattern
Unit 2 Session 1 (Click for link to problem statements)
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
schedulestring follows the same pattern as defined by thepatternstring. Each character inpatternshould map to a non-empty word inschedulewith a one-to-one correspondence.
- A: The problem asks to determine if a given
-
Q: What are the inputs?
- A: Two strings,
patternandschedule.
- A: Two strings,
-
Q: What are the outputs?
- A: A boolean value,
Trueif theschedulefollows the pattern, andFalseotherwise.
- A: A boolean value,
-
Q: Are there any constraints on the strings?
- A: Each character in
patternshould map to a unique word inscheduleand vice versa.
- A: Each character in
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.
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