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 = 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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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

1
2
3
4
5
6
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

1
2
3
4
5
6
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 <= 10^5
  • instructions[i] is either "add" or "jump".
  • -10^5 <= values[i] <= 10^5

Solution

Method 1 – Simulation with Visited Set

Intuition

We simulate the process step by step, tracking visited instructions to avoid revisiting. For each instruction, we either add to the score or jump, and stop if we go out of bounds or revisit an instruction.

Approach

  1. Initialize i = 0, ans = 0, and an empty set for visited indices.
  2. While i is in bounds and not visited:
    • Mark i as visited.
    • If instructions[i] is “add”:
      • Add values[i] to ans.
      • Move to i + 1.
    • If instructions[i] is “jump”:
      • Move to i + values[i].
  3. Return ans when the process ends.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    int calculateScore(vector<string>& instructions, vector<int>& values) {
        int n = instructions.size(), ans = 0, i = 0;
        unordered_set<int> vis;
        while (i >= 0 && i < n && !vis.count(i)) {
            vis.insert(i);
            if (instructions[i] == "add") {
                ans += values[i];
                i++;
            } else {
                i += values[i];
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func calculateScore(instructions []string, values []int) int {
    n, ans, i := len(instructions), 0, 0
    vis := make(map[int]bool)
    for i >= 0 && i < n && !vis[i] {
        vis[i] = true
        if instructions[i] == "add" {
            ans += values[i]
            i++
        } else {
            i += values[i]
        }
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int calculateScore(String[] instructions, int[] values) {
        int n = instructions.length, ans = 0, i = 0;
        Set<Integer> vis = new HashSet<>();
        while (i >= 0 && i < n && !vis.contains(i)) {
            vis.add(i);
            if (instructions[i].equals("add")) {
                ans += values[i];
                i++;
            } else {
                i += values[i];
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
    fun calculateScore(instructions: Array<String>, values: IntArray): Int {
        val n = instructions.size
        var ans = 0
        var i = 0
        val vis = mutableSetOf<Int>()
        while (i in 0 until n && i !in vis) {
            vis.add(i)
            if (instructions[i] == "add") {
                ans += values[i]
                i++
            } else {
                i += values[i]
            }
        }
        return ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def calculateScore(self, instructions: list[str], values: list[int]) -> int:
        n, ans, i = len(instructions), 0, 0
        vis = set()
        while 0 <= i < n and i not in vis:
            vis.add(i)
            if instructions[i] == "add":
                ans += values[i]
                i += 1
            else:
                i += values[i]
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use std::collections::HashSet;
impl Solution {
    pub fn calculate_score(instructions: Vec<String>, values: Vec<i32>) -> i32 {
        let n = instructions.len();
        let mut ans = 0;
        let mut i = 0i32;
        let mut vis = HashSet::new();
        while i >= 0 && (i as usize) < n && !vis.contains(&i) {
            vis.insert(i);
            if instructions[i as usize] == "add" {
                ans += values[i as usize];
                i += 1;
            } else {
                i += values[i as usize];
            }
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    calculateScore(instructions: string[], values: number[]): number {
        const n = instructions.length;
        let ans = 0, i = 0;
        const vis = new Set<number>();
        while (i >= 0 && i < n && !vis.has(i)) {
            vis.add(i);
            if (instructions[i] === "add") {
                ans += values[i];
                i++;
            } else {
                i += values[i];
            }
        }
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(n)
  • 🧺 Space complexity: O(n)