Check if a Signal Occurs as a Prefix in Any Transmission - codepath/compsci_guides GitHub Wiki

TIP102 Unit 3 Session 2 Standard (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 input to the problem?
    • A: The input consists of a string transmission, which contains signals separated by spaces, and a string searchSignal that needs to be checked as a prefix.
  • Q: What is the output?
    • A: The output is an integer representing the 1-indexed position of the first signal in transmission where searchSignal is a prefix. If no such signal exists, return -1.
  • Q: What is considered a prefix?
    • A: A prefix of a string is any leading contiguous substring of that string.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Split the transmission into individual signals, then iterate through each signal to check if searchSignal is a prefix. Return the index of the first match or -1 if no match is found.

1. Split the `transmission` string into a list of individual signals using the `split()` function.
2. Initialize an index variable to 1, as we need to return a 1-indexed position.
3. Iterate through the list of signals:
   1. If the current signal starts with `searchSignal`, return the current index.
   2. Increment the index by 1 for each signal checked.
4. If no signal matches the prefix, return `-1`.

⚠️ Common Mistakes

  • Misinterpreting the 1-indexed position requirement, leading to off-by-one errors.
  • Incorrectly checking the prefix using functions other than startswith, which may not correctly identify prefixes.
  • Forgetting to return -1 when no signal matches the prefix.

I-mplement

def is_prefix_of_signal(transmission, searchSignal):
    signals = transmission.split()
    index = 1

    for signal in signals:
        if signal.startswith(searchSignal):
            return index
        index += 1

    return -1

# Example usage
print(is_prefix_of_signal("i love eating burger", "burg"))  # Output: 4
print(is_prefix_of_signal("this problem is an easy problem", "pro"))  # Output: 2
print(is_prefix_of_signal("i am tired", "you"))  # Output: -1