- 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
- 41 lines of C++ from the credited upstream file smallest-range.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 2 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.
123 4class Solution {5public:6 vector<int> smallestRange(vector<vector<int>>& nums) {7 using VIT = vector<int>::iterator;8 9 const auto comp = [](const pair<VIT, VIT>& p1, const pair<VIT, VIT>& p2) {10 return *p1.first > *p2.first;11 };12 13 int left = numeric_limits<int>::max(), right = numeric_limits<int>::min();14 priority_queue<pair<VIT, VIT>, vector<pair<VIT, VIT>>, decltype(comp)> min_heap(comp);15 for (auto &row : nums) {16 left = min(left, row[0]);17 right = max(right, row[0]);18 min_heap.emplace(row.begin(), row.end());19 }20 21 vector<int> result = {left, right};22 while (!min_heap.empty()) {23 auto p = min_heap.top();24 min_heap.pop();25 ++p.first;26 if (p.first == p.second) {27 break;28 }29 min_heap.emplace(p);30 31 left = *min_heap.top().first;32 right = max(right, *p.first);33 if (right - left < result[1] - result[0]) {34 result = {left, right};35 }36 }37 return result;38 }39};40 41