LeetCode 821: Shortest Distance to a Character Solution

Master LeetCode problem 821 (Shortest Distance to a Character), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

821. Shortest Distance to a Character

Problem Explanation

Explanation

To solve this problem, we can iterate through the string s twice. In the first iteration, we find the distance to the closest occurrence of character c by going from left to right. In the second iteration, we find the distance from the closest occurrence of character c by going from right to left. We then take the minimum of these two distances at each index to get the final answer array.

  • Algorithm:

    1. Initialize two arrays left and right of size s.length() to store the distances from left and right respectively.
    2. Initialize variables prev and result to store the previous occurrence index of character c and the final answer array.
    3. Iterate through the string s from left to right, updating left and prev.
    4. Iterate through the string s from right to left, updating right and calculating the minimum distance.
  • Time Complexity: O(N) where N is the length of the input string s.

  • Space Complexity: O(N) for the two arrays left and right.

Solution Code

class Solution {
    public int[] shortestToChar(String s, char c) {
        int n = s.length();
        int[] ans = new int[n];
        int prev = Integer.MIN_VALUE / 2;

        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == c) {
                prev = i;
            }
            ans[i] = i - prev;
        }

        prev = Integer.MAX_VALUE / 2;
        for (int i = n - 1; i >= 0; i--) {
            if (s.charAt(i) == c) {
                prev = i;
            }
            ans[i] = Math.min(ans[i], prev - i);
        }

        return ans;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 821 (Shortest Distance to a Character)?

This page provides optimized solutions for LeetCode problem 821 (Shortest Distance to a Character) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 821 (Shortest Distance to a Character)?

The time complexity for LeetCode 821 (Shortest Distance to a Character) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 821 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 821 in Java, C++, or Python.

Back to LeetCode Solutions