Calculate Score After Performing Instructions solution and explanation
8 more videos on this problem
Q1. Calculate Score After Performing Instructions | Leetcode Contest Solution | @Solution_spotSolution Spot · 0:16 · 244 views
3522. Calculate Score After Performing Instructions (Leetcode Medium)Programming Live with Larry · 5:05 · 168 views
LeetCode 3522. Calculate Score After Performing Instructions | TC O(N) | SC O(N)Leet's Code · 12:04 · 165 views
Calculate Score After Performing Instructions LeetCode Weekly Contest 446R Sai Siddhu · 8:29 · 156 views
3522. Calculate Score After Performing InstructionsTech Courses · 4:22 · 93 views
Leetcode Weekly Contest 446 - Q1. Calculate Score After Performing InstructionsADevOpsEngineer · 5:03 · 82 views
3522. Calculate Score After Performing Instructions | Leetcode Weekly Contest 446Ujjwal Mishra · 12:14 · 43 views
3522. Calculate Score After Performing Instructions || C++ || 2 approaches explainedCodeQuest · 10:29 · 41 views
3522. Calculate Score After Performing Instructions #googleinterview #leetcode #java #dsa #dsalgoCodeVia · 4:19 · 23 views
The problem
You are given two arrays, instructions and values, both of size n.
You need to simulate a process based on the following rules:
- You start at the first instruction at index
i = 0with an initial score of 0. - If
instructions[i]is"add":- Add
values[i]to your score. - Move to the next instruction
(i + 1).
- Add
- If
instructions[i]is"jump":- Move to the instruction at index
(i + values[i])without modifying your score.
- Move to the instruction at index
The process ends when you either:
- Go out of bounds (i.e.,
i < 0 or i >= n), or - Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.
Return your score at the end of the process.
Example 1:
Input: instructions = ["jump","add","add","jump","add","jump"], values = [2,1,3,1,-2,-3]
Output: 1
Explanation:
Simulate the process starting at instruction 0:
- At index 0: Instruction is
"jump", move to index0 + 2 = 2. - At index 2: Instruction is
"add", addvalues[2] = 3to your score and move to index 3. Your score becomes 3. - At index 3: Instruction is
"jump", move to index3 + 1 = 4. - At index 4: Instruction is
"add", addvalues[4] = -2to your score and move to index 5. Your score becomes 1. - At index 5: Instruction is
"jump", move to index5 + (-3) = 2. - At index 2: Already visited. The process ends.
Example 2:
Input: instructions = ["jump","add","add"], values = [3,1,1]
Output: 0
Explanation:
Simulate the process starting at instruction 0:
- At index 0: Instruction is
"jump", move to index0 + 3 = 3. - At index 3: Out of bounds. The process ends.
Example 3:
Input: instructions = ["jump"], values = [0]
Output: 0
Explanation:
Simulate the process starting at instruction 0:
- At index 0: Instruction is
"jump", move to index0 + 0 = 0. - At index 0: Already visited. The process ends.
Constraints:
n == instructions.length == values.length1 <= n <= 105instructions[i]is either"add"or"jump".-105 <= values[i] <= 105
Approach overview
Problem Overview: You are given a sequence of instructions represented as a string and must simulate them step by step to calculate the final score. Each instruction updates the current state (such as position, value, or score), and repeated interactions often require tracking previously visited states.
Approach 1: Brute Force Simulation (O(n^2) time, O(1) space)
The straightforward method simulates every instruction exactly as described and recomputes the effect each time the score needs to be updated. For example, when an instruction references a previous state or repeated operation, you scan earlier operations to determine the contribution. This approach uses simple iteration over the instruction string and directly applies the rules without additional data structures. While easy to implement, repeated scans make the solution inefficient when the instruction list grows.
Approach 2: Optimized Simulation with Hash Table (O(n) time, O(n) space)
The efficient strategy still performs a step‑by‑step simulation but stores intermediate results in a hash table. As you iterate through the instruction string once, maintain the current score and update it based on the instruction. A hash map or set tracks previously processed states (such as visited positions or computed values), allowing constant‑time lookups instead of rescanning earlier steps. This eliminates redundant work and keeps each instruction processing to O(1). The algorithm mainly involves iterating through the instruction sequence, updating the running score, and performing hash lookups when an instruction references past information.
This pattern is common in problems involving arrays, strings, and instruction-driven simulation. The hash table acts as a fast cache for previously computed states, a typical optimization when repeated operations appear in instruction streams.
Recommended for interviews: The optimized simulation with a hash table is the approach interviewers expect. Starting with brute force demonstrates you understand the rules of the simulation. Transitioning to the O(n) approach shows you can recognize repeated work and eliminate it using a hash table for constant‑time lookups.
Solution
We can simulate the process based on the problem description.
Define a boolean array vis of length n to record whether each instruction has been executed. Initially, all elements are set to false.
Then, starting from index i = 0, perform the following steps in a loop:
- Set
vis[i]totrue. - If the first character of
instructions[i]is 'a', addvalue[i]to the answer and incrementiby1. Otherwise, incrementibyvalue[i].
The loop continues until i \lt 0, i \ge n, or vis[i] is true.
Finally, return the answer.
The time complexity is O(n), and the space complexity is O(n), where n is the length of the array value.
class Solution:
def calculateScore(self, instructions: List[str], values: List[int]) -> int:
n = len(values)
vis = [False] * n
ans = i = 0
while 0 <= i < n and not vis[i]:
vis[i] = True
if instructions[i][0] == "a":
ans += values[i]
i += 1
else:
i = i + values[i]
return ansclass Solution {
public long calculateScore(String[] instructions, int[] values) {
int n = values.length;
boolean[] vis = new boolean[n];
long ans = 0;
int i = 0;
while (i >= 0 && i < n && !vis[i]) {
vis[i] = true;
if (instructions[i].charAt(0) == 'a') {
ans += values[i];
i += 1;
} else {
i = i + values[i];
}
}
return ans;
}
}class Solution {
public:
long long calculateScore(vector<string>& instructions, vector<int>& values) {
int n = values.size();
vector<bool> vis(n, false);
long long ans = 0;
int i = 0;
while (i >= 0 && i < n && !vis[i]) {
vis[i] = true;
if (instructions[i][0] == 'a') {
ans += values[i];
i += 1;
} else {
i += values[i];
}
}
return ans;
}
};function calculateScore(instructions: string[], values: number[]): number {
const n = values.length;
const vis: boolean[] = Array(n).fill(false);
let ans = 0;
let i = 0;
while (i >= 0 && i < n && !vis[i]) {
vis[i] = true;
if (instructions[i][0] === 'a') {
ans += values[i];
i += 1;
} else {
i += values[i];
}
}
return ans;
}func calculateScore(instructions []string, values []int) (ans int64) {
n := len(values)
vis := make([]bool, n)
i := 0
for i >= 0 && i < n && !vis[i] {
vis[i] = true
if instructions[i][0] == 'a' {
ans += int64(values[i])
i += 1
} else {
i += values[i]
}
}
return
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Simulation | O(n^2) | O(1) | Useful for understanding the instruction rules or when the input size is very small |
| Simulation with Hash Table | O(n) | O(n) | Best general solution when instructions may reference previous states or repeated operations |
Frequently asked questions
Is Calculate Score After Performing Instructions easy or hard?
The problem is rated Medium because the implementation is straightforward but requires careful state management during simulation. Recognizing that repeated work can be optimized with a hash table is the key step that leads to the optimal O(n) solution.
Calculate Score After Performing Instructions Python/Java solution
The solution iterates through the instruction string and updates a running score while storing intermediate states in a hash table. The same logic translates directly across languages such as Python, Java, C++, Go, and TypeScript because it relies on basic loops and dictionary or map operations.
How to solve Calculate Score After Performing Instructions in O(n)?
Process the instruction string sequentially and maintain the current score as you simulate each operation. Store intermediate states or results in a hash table so that repeated references can be resolved instantly instead of rescanning earlier instructions. This ensures each step performs only constant-time work.
What is the best approach for Calculate Score After Performing Instructions?
The best approach is a single-pass simulation combined with a hash table to track previously processed states. Each instruction is processed once while the hash table enables constant-time lookups for repeated or referenced operations. This reduces redundant work and achieves O(n) time complexity with O(n) space.
Is Calculate Score After Performing Instructions asked at Google/Amazon/Meta?
Simulation and hash-table problems similar to this frequently appear in coding interviews at large tech companies such as Google, Amazon, and Meta. Interviewers often use them to evaluate how candidates manage state changes and optimize repeated operations in linear time.
What data structure is used in Calculate Score After Performing Instructions?
The primary data structures are arrays or strings for storing the instruction sequence and a hash table for tracking previously computed states. The hash table enables constant-time lookups during the simulation and avoids repeated scans of earlier instructions.
What is the time complexity of Calculate Score After Performing Instructions?
The optimal solution runs in O(n) time, where n is the number of instructions. Each instruction is processed once during the simulation, and hash table lookups occur in constant time on average. The space complexity is O(n) for storing previously encountered states or values.
