The trick here is to name the state correctly, then let the implementation follow. For 125. Valid Palindrome, 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?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are isPalindrome.
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:
- 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: 12 ms, faster than 78.77% of C++ online submissions for Valid Palindrome.
02//Memory Usage: 9.3 MB, less than 24.05% of C++ online submissions for Valid Palindrome.
03class Solution {
04public:
05 bool isPalindrome(string s) {
06 int i = 0, j = s.size()-1;
07 while(i < j){
08 while(i < s.size() && !isalnum(s[i]))i++;
09 while(j >= 0 && !isalnum(s[j]))j--;
10 // cout << i << " " << j << endl;
11 //we have scanned the whole string
12 if(i >= j) break;
13 //slower
14 // if(i >= s.size() || j < 0) break;
15 if(tolower(s[i]) != tolower(s[j])) return false;
16 i++; j--;
17 }
18 return true;
19 }
20};
Cost