This is one of those problems where the clean idea matters more than the amount of code. For 1503. Last Moment Before All Ants Fall Out of a Plank, the solution in this repository is mainly a two pointers solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. 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: two pointers, greedy.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are getLastMoment.
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:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
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: 124 ms, faster than 11.48% of C++ online submissions for Last Moment Before All Ants Fall Out of a Plank.
02//Memory Usage: 23 MB, less than 100.00% of C++ online submissions for Last Moment Before All Ants Fall Out of a Plank.
03class Solution {
04public:
05 int getLastMoment(int n, vector<int>& left, vector<int>& right) {
06 sort(left.begin(), left.end());
07 sort(right.begin(), right.end());
08
09 if(left.empty() && right.empty()){
10 return 0;
11 }else if(left.empty()){
12 return n - right[0];
13 }else if(right.empty()){
14 return left.back();
15 }
16
17 return max(n-right[0], left.back());
18 }
19};
Cost