Final challenge: the growing row
After this: Follow, cost, fix and implement array operations.
This challenge has four steps, and each step is scored on its own. You will follow a series of operations that makes the row grow, give the cost of three operations, find a bug in a loop, and write the line that makes insert work. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 4Trace it
Trace it
A dynamic array starts empty with capacity 2. Run: append 5, append 7, append 9, insert 6 at index 1, remove index 0. What are the capacity, the size and the row?
Cost it
For an array of n elements, pick the row that gives the right costs for: read by index, append, insert at the front.
Fix the loop
This is meant to remove every even number, but it prints [4, 8]. Why, and what is the right fix?
nums = [2, 4, 6, 8]for x in nums: # the loop walks by index while the list shifts under it if x % 2 == 0: nums.remove(x)print(nums)Output
[4, 8]
List<Integer> nums = new ArrayList<>(List.of(2, 4, 6, 8));for (int i = 0; i < nums.size(); i++) { // the index advances while the list shifts under it if (nums.get(i) % 2 == 0) { nums.remove(i); }}System.out.println(nums);Output
[4, 8]
Implement insert
Complete insert on a fixed-capacity row: the loop walks i from size down to index + 1, and each step moves the cell on the left into cell i.
def insert(cells, size, index, value): """Insert into a fixed-capacity row; the caller guarantees size < len(cells).""" for i in range(size, index, -1): ______________________________ # ← move the cell on the left one step right cells[index] = value return size + 1static int insert(int[] cells, int size, int index, int value) { // Insert into a fixed-capacity row; the caller guarantees size < cells.length. for (int i = size; i > index; i--) { ______________________________ // ← move the cell on the left one step right } cells[index] = value; return size + 1;}- Follow a sequence that makes the row grow, cost three operations, fix a loop and implement insert.