Array Element Modification

Visualization

[0]
[1]
[2]
[3]
[4]
10
20
30
40
50
Click 'Run' to visualize the modification
1

Array Element Modification

EasyArrays

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.

Input:arr = [10, 20, 30, 40, 50], index = 2, value = 99
Output:[10, 20, 99, 40, 50]
Solutions
solution.py
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]

Explanation

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.