- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 39 lines of C++ from the credited upstream file 1182.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> shortestDistanceColor(vector<int>& colors,4 vector<vector<int>>& queries) {5 constexpr int kNumColor = 3;6 const int n = colors.size();7 vector<int> ans;8 9 vector<vector<int>> left(n, vector<int>(kNumColor + 1));10 11 vector<vector<int>> right(n, vector<int>(kNumColor + 1));12 13 vector<int> colorToClosestIndex{0, -1, -1, -1}; 14 for (int i = 0; i < n; ++i) {15 colorToClosestIndex[colors[i]] = i;16 for (int c = 1; c <= kNumColor; ++c)17 left[i][c] = colorToClosestIndex[c];18 }19 20 colorToClosestIndex = {0, -1, -1, -1}; 21 for (int i = n - 1; i >= 0; --i) {22 colorToClosestIndex[colors[i]] = i;23 for (int c = 1; c <= kNumColor; ++c)24 right[i][c] = colorToClosestIndex[c];25 }26 27 for (const vector<int>& query : queries) {28 const int i = query[0];29 const int c = query[1];30 const int leftDist = left[i][c] == -1 ? INT_MAX : i - left[i][c];31 const int rightDist = right[i][c] == -1 ? INT_MAX : right[i][c] - i;32 const int minDist = min(leftDist, rightDist);33 ans.push_back(minDist == INT_MAX ? -1 : minDist);34 }35 36 return ans;37 }38};39