Calculate Score After Performing Instructions - Problem

You are given two arrays, instructions and values, both of size n. You need to simulate a process based on the following rules:

Starting conditions:

  • You start at the first instruction at index i = 0
  • Initial score is 0

Instruction processing:

  • If instructions[i] is "add": Add values[i] to your score and 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)
  • 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.

Input & Output

Example 1 — Basic Simulation
$ Input: instructions = ["add","jump","add"], values = [2,-1,3]
Output: 2
💡 Note: Start at i=0: execute 'add', score becomes 2, move to i=1. At i=1: execute 'jump', jump to i=0 (already visited). Process ends with score 2.
Example 2 — Out of Bounds
$ Input: instructions = ["add","jump"], values = [5,2]
Output: 5
💡 Note: Start at i=0: execute 'add', score becomes 5, move to i=1. At i=1: execute 'jump', jump to i=3 (out of bounds). Process ends with score 5.
Example 3 — Multiple Adds
$ Input: instructions = ["add","add","jump"], values = [1,2,-1]
Output: 3
💡 Note: i=0: add 1, score=1, move to i=1. i=1: add 2, score=3, move to i=2. i=2: jump to i=1 (already visited). Process ends with score 3.

Constraints

  • 1 ≤ instructions.length ≤ 104
  • instructions[i] is either "add" or "jump"
  • -104 ≤ values[i] ≤ 104

Visualization

Tap to expand
Calculate Score: Instruction Processing OverviewInstructions["add","jump","add"]Values[2, -1, 3]Simulation Process• Track visited positions• Execute add/jump instructions• Detect cycles and boundsFinal Score2Step-by-step: i=0 add(2)→score=2, i=1 jump(-1)→i=0 (visited), terminate
Understanding the Visualization
1
Input
Arrays of instructions and corresponding values
2
Process
Simulate execution while tracking visited positions
3
Output
Final score when process terminates
Key Takeaway
🎯 Key Insight: Use visited tracking to detect cycles and prevent infinite loops during simulation
Asked in
Amazon 15 Microsoft 12
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen