Given an integer array arr, transform it according to the following rule: whenever you encounter the value 2, insert another 2 immediately after it and remove the last element of the array to maintain the original size.
The transformation should be applied in a single left-to-right pass. A newly inserted 2 should not itself trigger another insertion. Return the transformed array.
For example, given [1, 2, 3, 4], after encountering the 2 we insert a 2 right after it and drop the last element, yielding [1, 2, 2, 3].
Function Signature
def transform_array(arr: list[int]) -> list[int]:
Rules
-
The returned list has the same length as
arr
.
-
Only the
2
s from the original array trigger an insertion. An original
2
that has already been pushed off the end by earlier insertions does not trigger anything.
-
If a
2
ends up in the last position, its inserted copy is the element that gets removed.
Constraints
-
1 <= len(arr) <= 10^5
-
-10^9 <= arr[i] <= 10^9
Examples
Input: arr = [1, 2, 3, 4]
Output: [1, 2, 2, 3]
Encountering the 2 inserts another 2 after it and drops the trailing 4, giving [1, 2, 2, 3].
Input: arr = [2, 3, 5, 2, 8, 7]
Output: [2, 2, 3, 5, 2, 2]
The first 2 inserts a 2 and drops 7, giving [2, 2, 3, 5, 2, 8]. The next original 2 inserts a 2 and drops 8, giving [2, 2, 3, 5, 2, 2].
Input: arr = [1, 3, 2]
Output: [1, 3, 2]
The 2 is already last. Inserting its copy makes the array [1, 3, 2, 2], and removing the last element removes that copy again.