Junior — Middle
How to determine the time complexity of an operation to replace an element in an array?
sobes.tech AI
Answer from AI
The time complexity of replacing an element in an array is usually O(1), that is, constant.
This is because arrays (for example, arrays in Swift or Objective-C) provide direct access to elements by index. To replace an element, it is enough to access the desired index and assign a new value, which takes constant time.
Example in Swift:
var array = [1, 2, 3, 4, 5]
array[2] = 10 // replacing the third element
Here, the replacement operation does not require shifting elements or reallocating memory, so its time complexity is O(1).