C++ 0682.cpp
class Solution {
public:
int calPoints(vector<string>& operations) {
vector<int> r;
for (auto o : operations)
{
if (o == "C")
{
r.pop_back();
continue;
}
if (o == "D")
{
r.push_back(2 * r.back());
continue;
}
if (o == "+")
{
r.push_back(r[r.size() - 2] + r[r.size() - 1]);
continue;
}
r.push_back(stoi(o));
}
int sum = 0;
for (auto x : r)
sum += x;
return sum;
}
};
Difficulty
and has an acceptance rate of about 80% (700k+ submissions).
Typical patterns to solve this problem:
- Array
- Simulation
- Stack
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves a scoring problem by iterating over a sequence of string operations, maintaining a dynamic list of integer scores, and finally aggregating the results. The algorithm relies on a single pass to interpret each operation and a second pass to compute the total. All state is kept in a vector<int> that grows and shrinks in response to the commands.
Core Logic
The heart of the solution is a loop that examines each token in the input vector operations. For every token the code decides which action to perform:
for (auto o : operations)
{
if (o == "C")
{
r.pop_back();
continue;
}
if (o == "D")
{
r.push_back(2 * r.back());
continue;
}
if (o == "+")
{
r.push_back(r[r.size() - 2] + r[r.size() - 1]);
continue;
}
r.push_back(stoi(o));
}
- When the token equals
"C"the most recent score is removed withpop_back(). - When the token equals
"D"the new score is twice the last recorded value, obtained viar.back(). - When the token equals
"+"the new score is the sum of the two most recent entries, accessed directly by index. - Any other token is interpreted as a numeric literal and converted to an integer with
stoi, then appended to the vector.
After processing all operations, the accumulated scores are summed:
int sum = 0;
for (auto x : r)
sum += x;
return sum;
The function returns this total as the final result.
Edge Cases Handled
The code implicitly accommodates several boundary conditions dictated by the problem constraints:
- Empty input - If
operationscontains no elements, the loop body never executes, leavingrempty. The subsequent summation loop iterates zero times, yielding a sum of0, which is a sensible default. - Single numeric entry - When the first token is a number,
stoiconverts it andpush_backstores it. Subsequent commands that rely on previous entries (e.g.,"D"or"+") will only be reached if enough prior scores exist, matching the expected input guarantees. - Immediate removal - A
"C"command can appear right after a numeric entry, causingpop_back()to delete the most recent score. The vector remains valid because the removal occurs only when at least one element is present, as ensured by the input specification. - Duplicate and sum operations -
"D"and"+"depend on the existence of one and two prior scores respectively. The code accessesr.back()andr[r.size() - 2]directly, which is safe under the assumption that the input never issues these commands without sufficient history.
Performance Considerations
The implementation exhibits several optimizations that keep the execution efficient:
- Amortized constant-time updates - Using
vector<int>withpush_backandpop_backprovides O(1) amortized insertion and removal at the end of the container, avoiding the overhead of more complex data structures. - Direct element access - The use of
r.back()and indexed accessr[r.size() - 2]eliminates the need for iterator traversal, delivering immediate retrieval of the required scores. - Early continuation - Each conditional block ends with
continue, preventing the evaluation of later conditions once a match is found. This reduces the number of comparisons per iteration. - Minimal parsing overhead - Conversion with
stoioccurs only for tokens that are not one of the three special commands, limiting the cost of string-to-integer parsing to the necessary cases. - Separate aggregation pass - Summing the final scores in a dedicated loop isolates the accumulation step from the command-processing logic, allowing the compiler to optimize each loop independently.
Overall, the algorithm runs in linear time relative to the number of operations, with memory usage proportional to the number of active scores stored in the vector. The straightforward use of standard library containers and functions contributes to both clarity and performance.
ELI5 - Simplified Explanation
Imagine there is a big list of chores that needs to be played like a game. The code uses a special box to keep track of points earned for these chores. The computer looks at each chore one by one to decide what to do with the points.
If the chore says the letter c, it means there was a mistake, so the computer takes the very last point out of the box and throws it away.
If the chore says the letter d, it means you get a double bonus. The computer looks at the last point in the box, copies it, makes it twice as big, and puts that new number in the box too.
If the chore says a plus sign, it means the computer looks at the two most recent points in the box, adds them together like a puzzle, and puts the total into the box as a brand new point.
If the chore is just a regular number, the computer simply takes that number and places it into the box.
After going through every single chore, the computer gathers up all the points sitting in the box and adds them all together to see what the final score is.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality