DSA FUNDAMENTALS › ARRAY BASICS
The value x = 3 names a one-based position, while array indices start at 0. Convert the position before touching the array: deletion index = x - 1, so the index to remove is 2. In [8, 3, 6, 2, 9], index 2 contains 6. The required active result is [8, 3, 2, 9] with logical length n = 4.
Writing 0 at index 2 does not remove the element. If you write array[2] = 0 and only decrease n, the first four active values become [8, 3, 0, 2]. The 6 is gone, but a hole remains, and the original last value 9 is no longer part of the active range. Deletion must preserve the order of the values after the removed position, so those values need to move left.
Start at the deletion index, x - 1, and copy the value from the slot immediately to its right. Continue while a right-hand slot still exists. For this array, the loop performs two assignments, because indices 3 and 4 are the values that follow index 2.
for (int i = x - 1; i < n - 1; i++) {
array[i] = array[i + 1];
}The first assignment is array[2] = array[3]. It copies 2 over 6, producing the temporary physical state [8, 3, 2, 2, 9]. The duplicate 2 is expected because the source at index 3 has not been cleared or moved yet. The second assignment is array[3] = array[4]. It copies 9 over the duplicate at index 3, producing [8, 3, 2, 9, 9]. Each value after the deleted one moved left once, and their order stayed the same.
What is the physical array state immediately after only array[2] = array[3] has executed?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
After both copies, the physical storage is [8, 3, 2, 9, 9]. The array still has five storage slots, but the deletion is complete only when the logical length changes from n = 5 to n = 4. The active array is therefore the values at indices 0 through 3: [8, 3, 2, 9].
The final 9 at index 4 is stale storage. It does not need to be erased, because n tells output and later operations where the active array ends. Any loop that processes this array must stop before index 4. Decreasing n before the shift would make the loop lose access to the last value needed for the copy.
Enter the logical length after the completed shift.
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Before calculating x - 1, reading array[x - 1], or changing n, check that 1 <= x && x <= n. For this example, x = 3 passes because 3 is between 1 and 5. The deletion then shifts the values and changes n to 4.
A position below 1 or above the current logical length is not part of the active array. If x is invalid, leave both the array [8, 3, 6, 2, 9] and n = 5 unchanged. This check prevents an invalid position from reading or writing outside the intended active range, and it prevents a failed deletion from silently changing the data.