The trick here is to name the state correctly, then let the implementation follow. For 1033. Moving Stones Until Consecutive, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are numMovesStones.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Moving Stones Until Consecutive.
02//Memory Usage: 7.7 MB, less than 100.00% of C++ online submissions for Moving Stones Until Consecutive.
03
04class Solution {
05public:
06 vector<int> numMovesStones(int a, int b, int c) {
07 vector<int> v = {a, b, c};
08 int least, most;
09 sort(v.begin(), v.end());
10
11 //move the two stones at endpoint one position by one position
12 most = (v[1]-v[0]-1) + (v[2]-v[1]-1);
13 if(most == 0){
14 //three stones are already consecutive
15 least = 0;
16 }else{
17 //for [1,5,8]:
18 //move 8 -> [1,2,5]
19 //move 5 -> [1,2,3]
20 least = min(v[1]-v[0]-1, v[2]-v[1]-1);
21 //if there are two consecutive stones, we only need to move the other stone to the next of them, so one move is enough
22 //if there are two stones with one empty position inside, we only need to put the other stone into that empty position, so one move is enough
23 //if there are no consecutive stones, we can do one move to make two stones consecutive
24 least = (least <= 1) ? 1 : 2;
25 }
26
27 return {least, most};
28 }
29};
Cost