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 After Performing Instructions INPUT instructions[] "add" "jump" "add" i=0 i=1 i=2 values[] 2 -1 3 Rules: - "add": score += values[i] - "jump": i = i + values[i] - Stop if out of bounds - Stop if revisiting index Initial State i = 0, score = 0 ALGORITHM STEPS 1 i=0: "add" score = 0 + 2 = 2, i = 1 visited[0] 2 i=1: "jump" i = 1 + (-1) = 0 visited[1] jump 3 i=0: Already visited! Stop execution 4 Return score Final score = 2 Execution Trace 0: add --> score=2, i=1 1: jump --> i=0 0: STOP (revisited) FINAL RESULT Execution Path i=0 +2 i=1 jump i=0 STOP Visited Set {0, 1} Score Calculation Only i=0 added to score 0 + 2 = 2 Output 2 Key Insight: Use a visited set/array to track executed instructions. The simulation stops when: 1) Index goes out of bounds (i < 0 or i >= n), OR 2) We revisit an already executed instruction. Time: O(n) - each instruction visited at most once. Space: O(n) for visited tracking. TutorialsPoint - Calculate Score After Performing Instructions | Optimized 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