Leetcode Problem 821. Shortest Distance to a Character

821. Shortest Distance to a Character

Leetcode Solutions

Two-Pass Approach for Shortest Distance to a Character

  1. Initialize an array answer of the same length as s with all elements set to a large number (e.g., s.length).
  2. Set prev to a large negative value to represent that we haven't seen the character c yet.
  3. Iterate over s from left to right. For each index i, if s[i] is c, update prev to i. Then set answer[i] to i - prev.
  4. Set prev to a large positive value to represent that we haven't seen the character c from the right.
  5. Iterate over s from right to left. For each index i, if s[i] is c, update prev to i. Then update answer[i] to the minimum of answer[i] and prev - i.
  6. Return the answer array.
UML Thumbnail

Brute Force Approach for Shortest Distance to a Character

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...