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:
- Initialize two arrays
leftandrightof sizes.length()to store the distances from left and right respectively. - Initialize variables
prevandresultto store the previous occurrence index of charactercand the final answer array. - Iterate through the string
sfrom left to right, updatingleftandprev. - Iterate through the string
sfrom right to left, updatingrightand calculating the minimum distance.
- Initialize two arrays
-
Time Complexity: O(N) where N is the length of the input string
s. -
Space Complexity: O(N) for the two arrays
leftandright.
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.