Navigating the Research Station - codepath/compsci_guides GitHub Wiki

U-nderstand

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

  • Q
    • What is the desired outcome?
      • To calculate the total time to visit all required observation points in a given order.
    • What input is provided?
      • A string station_layout representing the layout of observation points, and a string observations representing the order of required observations.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Map each letter in station_layout to its index, then calculate the total time to move from one observation point to another based on observations.

1) Create a dictionary `layout_index` to map each letter in `station_layout` to its index.
2) Initialize `current_index` to 0 and `total_time` to 0.
3) Iterate through `observations`:
   - For each character, find its index in `station_layout`.
   - Calculate the time to move to the new index and add it to `total_time`.
   - Update `current_index` to the new index.
4) Return `total_time`.

⚠️ Common Mistakes

  • Not correctly mapping each letter to its index in the layout.

I-mplement

def navigate_research_station(station_layout, observations):
    # Create a dictionary to map each letter to its index in the station layout
    layout_index = {}
    for idx, char in enumerate(station_layout):
        layout_index[char] = idx
    
    # Initialize the starting index (initially at 0)
    current_index = 0
    total_time = 0
    
    # Iterate through each character in the observations string
    for char in observations:
        # Find the index of the current character in the station layout
        target_index = layout_index[char]
        
        # Calculate the time taken to move to the target index
        total_time += abs(current_index - target_index)
        
        # Update the current index to the target index
        current_index = target_index
    
    return total_time