Leetcode 821. Shortest Distance to a Character
Given a string s and a character c that occurs in s, return an array of integers representing the shortest distance from the character c in the string.
Input: s = "loveleetcode", c = 'e'
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Input: s = "aaab", c = 'b'
Output: [3,2,1,0]
s?
s will be in the range [1, 10^4].s lowercase English letters?
s are lowercase English letters.c always appear in the string s?
c always appears at least once in the string s.s contains only the character c?
s, since the distance to c is zero at every position.To solve the problem efficiently, we will:
result of the same length as s with large values (like infinity).c considering only the previous occurrences of c.c.c.result array with this distance for each position.c.result array to ensure the shortest distance is recorded for each position.n is the length of the string s, due to the two linear passes through the string.#include <vector>
#include <string>
#include <algorithm>
#include <climits>
std::vector<int> shortestToChar(const std::string &s, char c) {
int n = s.size();
std::vector<int> result(n, INT_MAX);
// Forward pass
int prev = -INT_MAX;
for (int i = 0; i < n; ++i) {
if (s[i] == c) {
prev = i;
}
result[i] = std::min(result[i], abs(i - prev));
}
// Backward pass
prev = INT_MAX;
for (int i = n - 1; i >= 0; --i) {
if (s[i] == c) {
prev = i;
}
result[i] = std::min(result[i], abs(i - prev));
}
return result;
}
By structuring the solution in two passes, we ensure the correct shortest distance is captured for each position in the string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?