#3522
Calculate Score After Performing Instructions
MediumArrayHash TableStringSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach efficiently tracks visited instructions using a set, ensuring each instruction is processed only once. It leverages direct index manipulation for jumps.
⚙️
Algorithm
3 steps- 1Step 1: Initialize score and a set to track visited indices.
- 2Step 2: Iterate through instructions, updating score and index based on instruction type.
- 3Step 3: Stop when out of bounds or revisiting an index.
solution.py14 lines
1def calculateScore(instructions, values):
2 score = 0
3 visited = set()
4 i = 0
5 while 0 <= i < len(instructions):
6 if i in visited:
7 break
8 visited.add(i)
9 if instructions[i] == 'add':
10 score += values[i]
11 i += 1
12 elif instructions[i] == 'jump':
13 i += values[i]
14 return scoreℹ
Complexity note: The complexity is linear as each instruction is processed once, and the set allows for O(1) average time complexity for checks.
- 1Tracking visited indices prevents infinite loops.
- 2Direct index manipulation allows efficient jumps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.