Update Element in Array

Say you have a list of exam scores in an array. Alex’s score got typed in wrong. You do not want to rebuild the whole list. You just want to fix that one spot. That fix is called updating an element.

Updating means changing the value that is already stored at a position in the array. The good news is that this is one of the fastest things an array can do. Let’s see why. Then we will write the code in five languages.

🎯 What Does β€œUpdate” Mean Here

Updating an element is simple. You pick a position. You put a new value there. The old value is gone.

The position is called the index. An index is just the number that tells the array which slot you mean. In most languages the first slot is index 0. The next one is index 1. And so on.

So say the array is [10, 20, 30, 40] and you update index 2 with the value 99. Now you get [10, 20, 99, 40]. Only that one slot changed. Everything else stayed the same.

⚑ Why Update Is So Fast

Here is the nice part. Updating an element takes the same tiny amount of time no matter how big the array is. We call that O(1). It means constant time.

Why is it that fast? It comes down to how arrays sit in memory.

  • All the elements live next to each other in one block of memory.
  • The computer knows where the block starts.
  • So to reach index i, it goes straight to β€œstart + i steps”. There is no searching.

This is called direct indexed access. The computer does not check each element one by one. It goes straight to the slot. Then it drops the new value in.

index 0: 10

index 1: 20

index 2: 30 -> 99

index 3: 40

Go straight to the index

The computer reaches any index in one step. It does not check each element first. That single step is why both reading and updating an element are O(1).

πŸ›‘οΈ Check the Index First

There is one trap here. The index you ask for must actually exist in the array. If the array has 4 elements, the valid indexes are 0, 1, 2, and 3. There is nothing at index 7. There is nothing at index -1 either.

What happens if you try to write to an index that does not exist? In C or C++ you might quietly damage other memory. In Java or Python you get a crash with an error. Either way, it is a real bug.

So before you write the value, you check that the index is in range. The rule is simple. The index must be 0 or greater. And it must be less than the size of the array.

  • If the index is valid, write the new value.
  • If the index is not valid, print an error and do nothing.

This check is what makes updateAt safe to call with any number.

Steps to update an element in an array

Before we write code, let’s lay out the steps.

  1. Create a function updateAt(array, index, value).
  2. Inside updateAt:
    • Check if the index is valid. It must be 0 or greater, and less than the array size.
    • If the index is not valid, print an error and return.
    • If the index is valid, assign the new value: array[index] = value.
  3. Inside the main function:
    • Create an array with some starting values.
    • Print the array before the update.
    • Call updateAt with an index and a new value.
    • Print the array after the update so you can see the change.

⌨️ Code to Update an Element in an Array

Now let’s see this in different programming languages. Notice how the update itself is just one line. The rest is the safety check and the printing.

Program to update element in array in Python

UpdateAt.py
# function to update element at a given index
def update_at(arr, index, value):
# Check if the index is valid
if index < 0 or index >= len(arr):
print(f"Invalid index {index}. Cannot update.")
return
# Index is valid, so assign the new value
arr[index] = value
def main():
arr = [10, 20, 30, 40]
print("Before update:", arr)
# Update index 2 with value 99
update_at(arr, 2, 99)
print("After update: ", arr)
# Try an invalid index
update_at(arr, 7, 50)
if __name__ == "__main__":
main()

The output of the above code will be:

Before update: [10, 20, 30, 40]
After update: [10, 20, 99, 40]
Invalid index 7. Cannot update.

Complexity Analysis for Updating an Element in an Array

Time Complexity:

  • O(1) - The computer goes straight to the index and writes the value. There is no loop over the elements, so the time does not grow with the array size. Space Complexity:
  • O(1) - We change a slot that already exists. We do not create any extra space that grows with the input.

⚠️ Common Mistakes

A few small things trip people up when updating. Watch out for these.

  • Forgetting the index check. Writing to an index that does not exist crashes the program or damages memory. Always check the range first.
  • Off-by-one on the last index. The last valid index is size - 1, not size. If the array has 4 elements, the last index is 3.
  • Confusing the index with the value. The index is the position. The value is what goes there. Mix up the two and you write the right number to the wrong spot.
  • Thinking update is slow. It is not. Update is O(1). It is inserting and deleting in the middle that cost O(n), because of all the shifting.

πŸ“Š Complexity Table for Update in Array

Operation Time Complexity Space Complexity
Update element at index O(1) O(1)

🧩 What You’ve Learned

You can now change a value in an array safely and quickly. Here is what you picked up.

  • βœ… Updating means putting a new value at an index that already exists, replacing the old value.
  • βœ… Arrays give direct indexed access, so update is O(1) constant time no matter the size.
  • βœ… Always check the index is valid first. It must be 0 or greater, and less than the array size.
  • βœ… The update itself is just one line: array[index] = value.
  • βœ… An invalid index should print an error and do nothing. It must never write out of range.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What is the time complexity of updating an element at a given index in an array?

    Why: Arrays support direct indexed access, so the computer goes straight to the index and writes the value in constant time.

  2. 2

    Why can an array reach any index so fast?

    Why: Because the elements are stored next to each other, the address of any index is start plus offset, reached in one step.

  3. 3

    For an array of size 4, which is a valid index to update?

    Why: Valid indexes run from 0 to size minus 1, so for size 4 the last valid index is 3.

  4. 4

    What should updateAt do when given an index that is out of range?

    Why: Writing out of range crashes the program or damages memory, so the safe move is to report the error and make no change.

πŸš€ What’s Next?

You can update any single element now. Next, learn how to visit every element, and how to remove one.

Share & Connect