PracticeArrays

Add a Document's Token Span

BeginnerArraystraversalaccumulationstate tracking Time not estimated Not started

Context

A document analysis tool assigns each token an integer impact score. For one review request, the tool receives the scores and the positions of the first and last token in a highlighted span. Compute the span's combined impact score.

Problem

Given a non-empty list of integer token scores and two valid positions, return the sum of all scores from start through end, including both endpoints. The positions are zero-based, start is no greater than end, and every position in the requested interval is valid. Count each position exactly once, including repeated values, zeros, and negative scores.

Examples

Example 1
Input: end = 3scores = [4, 7, 2, 9]start = 1
Output: 18
Explanation: Example 1 returns 18 when the scores from positions 1 through 3 are processed. (fact_ids: )
Example 2
Input: end = 3scores = [5, -3, 0, -3, 5]start = 1
Output: -6
Explanation: Example 2 returns -6 when the scores from positions 1 through 3 are processed, including repeated negative values and zero. (fact_ids: )
Example 3
Input: end = 0scores = [8, -2, 6]start = 0
Output: 8
Explanation: Example 3 returns 8 when the interval contains only position 0. (fact_ids: )

Constraints

  • 1 <= len(scores) <= 100000
  • -1000000 <= scores[i] <= 1000000 for every i
  • 0 <= start <= len(scores) - 1
  • 0 <= end <= len(scores) - 1
  • Types: scores is int[], start is int, end is int; result is int

Function signature

def sum_token_span(scores: list[int], start: int, end: int) -> int
scores list[int]
Integer impact score for each document token, in document order.
start int
Zero-based position of the first token in the inclusive span.
end int
Zero-based position of the last token in the inclusive span.
returns int
The total of all token scores at positions from start through end, inclusive.

Adapted from MBPP problem task_170 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Notes

  • Inputs guarantee start is no greater than end.
  • The interval is guaranteed to contain valid positions.
Approved · cb050r1-abs_624_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1