Shortest Distance to Character (Queue)

Data Structures
Easy
Netflix
124.5K views

Given a string $S$ and a character $C$, return an array of integers representing the shortest distance from each character in $S$ to the character $C$. Use a two-pass linear scan or BFS.

Why Interviewers Ask This

Netflix values engineers who prioritize performance and scalability in high-traffic environments. This question tests your ability to optimize time complexity from O(N^2) to O(N) using efficient data structures like queues or two-pointer techniques. It evaluates whether you can handle string manipulation problems with linear scans, a common requirement for their content delivery systems.

How to Answer This Question

1. Clarify requirements immediately: confirm if the string contains only C, what happens if C is missing, and input constraints. 2. Propose a brute-force solution first to show baseline understanding, then immediately pivot to an optimized approach. 3. Explain the Two-Pass strategy: one forward pass tracking the distance from the last seen C, and one backward pass updating distances from the next C. 4. Alternatively, describe the Queue approach where you store indices of C and calculate distances for non-C characters. 5. Walk through a concrete example step-by-step on a virtual whiteboard, showing how the array updates at each index. 6. Analyze space and time complexity, emphasizing why O(N) is critical for Netflix's scale. 7. Write clean, readable code with proper variable names.

Key Points to Cover

  • Demonstrating immediate recognition of the O(N) optimization over brute force
  • Clearly articulating the logic behind the two-pass scanning technique
  • Handling edge cases like missing target characters or single occurrences
  • Explicitly stating Time Complexity as O(N) and Space Complexity as O(1)
  • Connecting the efficiency gain to real-world high-scale data processing

Sample Answer

To solve the Shortest Distance to Character problem efficiently, I would first clarify that we need an O(N) solution since Netflix handles massive datasets. A naive approach checking every character against every occurre…

Common Mistakes to Avoid

  • Using nested loops resulting in O(N^2) time complexity without realizing it
  • Forgetting to handle the case where the target character appears only once
  • Not initializing the result array correctly, leading to incorrect distance calculations
  • Overcomplicating the solution with unnecessary data structures like full BFS when simple arrays suffice

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 161 Data Structures questionsBrowse all 45 Netflix questions