|
| 1 | +# [Problem 3379: Transformed Array](https://leetcode.com/problems/transformed-array/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +We are given a circular array and for each index i we should move nums[i] steps (right for positive, left for negative) and set result[i] to the value at the landing index. This is independent per index, so we don't mutate nums as we go. The circular movement suggests using modulo arithmetic to wrap indices. If nums[i] is 0, result[i] is 0 (which also matches taking the value at the landing index i). Steps may be larger than array length, so we should reduce steps modulo n. |
| 5 | + |
| 6 | +A straightforward approach: for each i compute target = (i + nums[i]) % n and set result[i] = nums[target]. Python's % handles negative values in the desired wrap-around way. |
| 7 | + |
| 8 | +## Refining the problem, round 2 thoughts |
| 9 | +- No need for any fancy data structures, just an output array of same length. |
| 10 | +- Handle negative nums and large steps via modulo. |
| 11 | +- Edge cases: n == 1 (works fine), nums[i] == 0 (either special-case or handled by same formula). |
| 12 | +- Time complexity should be O(n), space O(n) for the output. |
| 13 | +- Confirm: we must not change nums during computation (independent actions) — so always read from the original nums. |
| 14 | + |
| 15 | +## Attempted solution(s) |
| 16 | +```python |
| 17 | +from typing import List |
| 18 | + |
| 19 | +class Solution: |
| 20 | + def transformedArray(self, nums: List[int]) -> List[int]: |
| 21 | + """ |
| 22 | + Compute the transformed array as described: |
| 23 | + For each i, move nums[i] steps from i in the circular array and set result[i] |
| 24 | + to the value at the landing index. |
| 25 | + """ |
| 26 | + n = len(nums) |
| 27 | + result = [0] * n |
| 28 | + for i, step in enumerate(nums): |
| 29 | + # compute landing index with wrap-around; Python's % handles negatives properly |
| 30 | + target = (i + step) % n |
| 31 | + result[i] = nums[target] |
| 32 | + return result |
| 33 | + |
| 34 | +# Example usage: |
| 35 | +if __name__ == "__main__": |
| 36 | + sol = Solution() |
| 37 | + print(sol.transformedArray([3, -2, 1, 1])) # [1, 1, 1, 3] |
| 38 | + print(sol.transformedArray([-1, 4, -1])) # [-1, -1, 4] |
| 39 | +``` |
| 40 | +- Notes: |
| 41 | + - The core idea is using modulo arithmetic: target = (i + nums[i]) % n. This naturally handles positive, negative, and large-step values. |
| 42 | + - Time complexity: O(n), since we visit each index exactly once. |
| 43 | + - Space complexity: O(n) for the result array (plus O(1) extra). |
| 44 | + - We do not mutate the input nums while computing results, matching the "independent actions" requirement. |
0 commit comments