Given an array of integers, modify the element at a specific index with a new value. Return the modified array without mutating the original input.
arr = [10, 20, 30, 40, 50], index = 2, value = 99[10, 20, 99, 40, 50]def modify_array(arr: list, index: int, value: int) -> list:
"""
Modify an element at a specific index in the array.
Args:
arr: The input array
index: The index to modify (0-based)
value: The new value to set
Returns:
The modified array
"""
# Create a copy to avoid modifying the original
result = arr.copy()
# Check if index is valid
if 0 <= index < len(result):
result[index] = value
return result
# Example usage
numbers = [10, 20, 30, 40, 50]
modified = modify_array(numbers, 2, 99)
print(f"Original: {numbers}") # [10, 20, 30, 40, 50]
print(f"Modified: {modified}") # [10, 20, 99, 40, 50]In Python, we create a copy of the array using .copy() to avoid mutating the original. We then validate the index bounds before assignment. The time complexity is O(n) for the copy operation, and O(1) for the actual modification. This approach is safe and maintains immutability of the original data.