You are given an integer array stream representing a sparse stream of code tokens, where most values are zero. Transform it in a single pass according to these rules:
-
Compress any run of consecutive zeros into a single negative integer equal to the negation of the run length (for example, four zeros in a row become
-4
).
-
Replace every non-zero token with its square (for example,
3
becomes
9
and
-2
becomes
4
).
-
Preserve the relative order of the elements as they appear in the stream.
Return the transformed array.
Function Signature
def transform_stream(stream: list[int]) -> list[int]:
Rules
-
A run of zeros is a maximal block of consecutive zeros, so each run produces exactly one negative value in the output.
-
Each non-zero token produces exactly one value (its square), even when several non-zero tokens are adjacent.
-
An empty stream returns an empty list.
Constraints
-
0 <= len(stream) <= 10^5
-
-10^4 <= stream[i] <= 10^4
Examples
Input: stream = [0,0,0,3,0,0,-2,0]
Output: [-3,9,-2,4,-1]
The three leading zeros become -3, then 3 squared is 9. The next two zeros become -2, -2 squared is 4, and the single trailing zero becomes -1.
Input: stream = [5,0,0,0,0,7]
Output: [25,-4,49]
5 squared is 25, the four zeros in the middle become -4, and 7 squared is 49.
Input: stream = [-1,1,0,0,0,0,0]
Output: [1,1,-5]
The two adjacent non-zero tokens each become 1, and the five trailing zeros form one run that becomes -5.