The trick here is to name the state correctly, then let the implementation follow. For 168. Excel Sheet Column Title, 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:
- https://leetcode.com/problems/excel-sheet-column-title/discuss/441430/Detailed-Explanation-Here's-why-we-need-n-at-first-of-every-loop-(JavaPythonC%2B%2B)
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 convertToTitle.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- 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//https://leetcode.com/problems/excel-sheet-column-title/discuss/441430/Detailed-Explanation-Here's-why-we-need-n-at-first-of-every-loop-(JavaPythonC%2B%2B)
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Excel Sheet Column Title.
03//Memory Usage: 6 MB, less than 100.00% of C++ online submissions for Excel Sheet Column Title.
04class Solution {
05public:
06 string convertToTitle(int n) {
07 string ans;
08
09 /*
10 For string ABZ,
11 it is n = (0+1)*26^2 + (1+1)*26^2 + (25+1)*26^0,
12 to get 'Z'(which is 25),
13 we operate on the equation above:
14 n-1 = (0+1)*26^2 + (1+1)*26^2 + 25,
15 so we do (n-1)%26 to get the last char, which is 'Z' (1)
16
17 then to go to the next iteration,
18 we need to make n = (0+1)*26^2 + (1+1)*26^2,
19 we do this by n = (n-1)/26 (2)
20 */
21 while(n){
22 // cout << n%26 << " ";
23 ans.insert(ans.begin(), 'A' + (n-1)%26);
24 n = (n-1)/26;
25 }
26 // cout << endl;
27
28 return ans;
29 }
30};
Cost