As in Chapter 1, for each state of the garage, we can think of an optimal solution as consisting of performing \(|i-K|\) shift moves to arrive at some target row \(i\) (such that \(0 \le i \le R+1\)), followed by the removal of every car ultimately present in row \(K\). Let \(V_i\) be the total number of moves required to use target row \(i\). Initially, assuming no cars, \(V_i = |i-K|\). We'll then need to maintain the values \(V_{0..(R+1)}\) based on cars getting added or removed (including adding each car initially present in the garage), and be able to query the minimum of these values to compute each required \(M\) value. To help with this, we'll maintain a [segment tree](https://en.wikipedia.org/wiki/Segment_tree) over the \(V\) values, with each segment tree node storing the minimum of the values in its interval. Along the way, for each column \(j\), we'll need to be able to efficiently determine the row \(A_j\) of its \((R-K+1)\)th car from the top (if any), and the row \(B_j\) of its \(K\)th car from the bottom (if any). These are important because the column contributes \(1\) car for each target row \(i\) such that \(i < A_j\), \(i > B_j\), and/or \(G_{i,j} =\) "X". One approach is to maintain an ordered set of car positions in each column, pre-populated with \(R-K+1\) dummy cars above row \(1\) and \(K\) below row \(R\), and with pointers to the two relevant cars maintained. Another approach involves order statistics using a Fenwick (binary indexed) tree. Either way, we'll be able to add/remove cars and determine \(A_j\) and \(B_j\) in at most \(O(\log(R))\) time each. What remains is updating all of the above whenever a car gets added or removed. Each time this occurs, a single \(G\) value changes, and a single column's \(A\) and \(B\) values may change. This can be translated into at most \(3\) increments or decrements of ranges of \(V\) values, which can each be handled in \(O(\log(R))\) time using lazy propagation. The overall time complexity of this solution is therefore \(O((R\cdot C + S) \log(R))\). As in Chapter 1, it can also be observed that only target rows within \(C\) rows of row \(K\) need to be considered, as shifting to further target rows must take longer than sticking with a target row of \(K\) and removing all its cars. This opens the door to an \(O(S\cdot\min(R, C) + (R\cdot C + S) \log(R))\) variation on the above solution, in which the segment tree is removed in favour of simply iterating over all individual \(V\) values within the relevant interval of rows to update and query them. [See David Harmeyer (SecondThread)'s solution video here.](https://youtu.be/o9PqijKhax0?t=404)