Let's make this one less mysterious. For 941. Valid Mountain Array, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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.
The notes already sitting in the source point us in the right direction:
- One Pass
- time: O(n), space: O(1)
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are validMountainArray.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- 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:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
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), space: O(1)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//One Pass
02//time: O(n), space: O(1)
03//Runtime: 36 ms, faster than 80.51% of C++ online submissions for Valid Mountain Array.
04//Memory Usage: 10.4 MB, less than 100.00% of C++ online submissions for Valid Mountain Array.
05
06class Solution {
07public:
08 bool validMountainArray(vector<int>& A) {
09 if(A.size() < 3) return false;
10 int i = 1;
11 while(i < A.size() && A[i] > A[i-1]){
12 i++;
13 }
14 //i == 1 means A[1] <= A[0]
15 //while loop terminate because the array has been scanned
16 if(i == 1 || i == A.size()) return false;
17
18 while(i < A.size() && A[i] < A[i-1]){
19 i++;
20 }
21 //while loop terminate because the array has been scanned
22 if(i == A.size()) return true;
23 //while loop terminate because A[i] < A[i-1] not holds
24 return false;
25 }
26};
Cost