Array
Массив
This data structure keeps items in order and lets you read one directly by its position, called an index. In a zero-based array, index 0 refers to the first item and index 1 refers to the second.
An index is a position, not a value
Think of an array as a row of numbered slots. Two slots can hold the same value, but each has its own index. In a zero-based array of length n, valid indices run from 0 through n - 1. For example, an array of seven daily temperatures has indices 0 through 6. Reading index 3 gives you the fourth reading; finding the first day that reached 25 degrees is a different operation.
Why indexed access is fast
A conventional array lays out equal-sized slots next to one another in memory. To locate a slot, the program adds the index multiplied by the slot size to the starting address. It does the same amount of work whether you ask for the first slot or the millionth, so reading or replacing an item at a valid index takes O(1) time. An array can also store references: the slots are contiguous even when the objects they refer to are scattered in memory.
Fixed length versus room to grow
A Java array such as int[] has a fixed length once created. A dynamic array, such as C++ std::vector, tracks both its size (items currently stored) and its capacity (slots available before it needs a bigger buffer). Appending into spare capacity takes constant time. When the buffer fills, growing it requires moving or copying the existing items into a larger buffer. If capacity grows by a constant factor, such as doubling, a sequence of n appends to an initially empty array takes O(n) total time. That's O(1) amortized per append, even though an individual append can take O(n).
Example: removing an item
std::vector<int> readings{18, 21, 19, 24};
int second = readings[1]; // 21
readings.erase(readings.begin() + 1); // {18, 19, 24}
Reading the second item is constant time. Erasing it while preserving order shifts 19 and 24 one slot to the left. For a larger array, a middle insertion or removal can shift a number of items proportional to the array's size, giving O(n) worst-case time.
When arrays are a good fit
Arrays work well for lookup tables, sample buffers, and other data you access by position or scan in order. Sequential scans of contiguous slots also tend to make good use of the CPU cache. If you need to find an arbitrary value in an unsorted array, a linear search can inspect every item. If the array is sorted, binary search cuts that lookup to O(log n).
In an interview
State which operation you're analyzing and what you know up front: an index, a value, or the fact that the data is sorted. If you're writing a loop, test it with an empty array and a one-item array. For a zero-based array, i < n keeps the loop from trying to read a[n], which is one slot past the end.