Skip to main content

Calculate Score After Performing Instructions - Solution & Explanation

MediumArrayHash TableStringSimulation8 min readAsked at: Apple
Practice this problem

Problem Statement

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 = 0 with an initial score of 0.
  • If instructions[i] is "add":
    • Add values[i] to your score.
    • Move to the next instruction (i + 1).
  • If instructions[i] is "jump":
    • Move to the instruction at index (i + values[i]) without modifying your score.

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 index 0 + 2 = 2.
  • At index 2: Instruction is "add", add values[2] = 3 to your score and move to index 3. Your score becomes 3.
  • At index 3: Instruction is "jump", move to index 3 + 1 = 4.
  • At index 4: Instruction is "add", add values[4] = -2 to your score and move to index 5. Your score becomes 1.
  • At index 5: Instruction is "jump", move to index 5 + (-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 index 0 + 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 index 0 + 0 = 0.
  • At index 0: Already visited. The process ends.

 

Constraints:

  • n == instructions.length == values.length
  • 1 <= n <= 105
  • instructions[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:

  1. Set vis[i] to true.
  2. If the first character of instructions[i] is 'a', add value[i] to the answer and increment i by 1. Otherwise, increment i by value[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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force SimulationO(n^2)O(1)Useful for understanding the instruction rules or when the input size is very small
Simulation with Hash TableO(n)O(n)Best general solution when instructions may reference previous states or repeated operations

Video Solution

Q1. Calculate Score After Performing Instructions | Leetcode Contest Solution | @Solution_spot • Solution Spot • 244 views views

Watch 8 more video solutions →

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.

Ready to solve this problem?

Practice Calculate Score After Performing Instructions with our built-in code editor and test cases.

Practice on FleetCode