algoritmauzmanı
Sign in
TREN
2.4Exam Practice
Lesson 2.4.1

Arrays: exam questions and answers

In data structures exams almost always come first, and the questions fall into a few patterns: concepts, address calculation, tracing, code reading, code writing and complexity. This page has original questions of each kind with step-by-step answers.

What you will learn
  • Row-major and column-major address calculation, including indices that do not start at zero
  • How to trace shifting during insertion and deletion, and how to write short array functions in an exam
  • How to justify the complexity of array operations and the amortized O(1) append of a dynamic array
20 min

1Concept questions

Try each question yourself first, then open the box to check the answer. The questions were written for this site; their types are the ones that come up often in university midterm and final exams. The code uses the names from the array operation lessons: CAPACITY, arr, size, pos, value.

1List the differences between an array and a linked list. When would you choose an array, and when a linked list? Give an example of each.Midterm · concept

An array keeps its elements in , so it reaches the k-th element in time, but it has to shift elements when you insert at the front or in the middle. A linked list keeps each element in its own node; inserting in the middle means changing a few pointers, but reaching the k-th element means walking from the front.

CriterionArraySingly linked list
Access to the k-th elementO(1), address is computedO(n), walk from the front
Insert at the frontO(n), everything shiftsO(1)
Insert after a known nodeO(n), the rest shiftsO(1)
SizeFixed up frontGrows as nodes are added
Extra memoryNone, but unused capacity may be wastedOne pointer per node
Cache friendlinessGoodPoor

Example: a million sensor readings that are read by index all the time fit an array. In a text editor where lines are constantly inserted and deleted at the cursor, a linked list fits better. The full comparison is in the introduction to linked lists.

2An array declared with #define CAPACITY 8 holds 5 elements. What are its size and capacity? What happens if insertAtEnd is called 4 times in a row?Midterm · concept

Capacity is the number of cells reserved for the array: 8. Size is how many of those cells are actually in use: 5. The 3 empty cells are reserved but are not part of the array's contents.

  1. Call 1: size 5 < 8, the value goes into cell 5, size becomes 6, returns true.
  2. Call 2: size becomes 7, returns true.
  3. Call 3: size becomes 8, returns true. The array is now full.
  4. Call 4: size == CAPACITY, nothing is written, size stays 8, returns false.

A fixed array never changes its capacity. If you want it to grow when full, you use a dynamic array.

3Why does an array in C start at 0? What would change if it started at 1?Midterm · concept

The index tells how far an element is from the start of the array. The of element i is base + i × element_size. The first element sits at the start, so its distance is 0, and the formula needs no extra step.

In C, writing a[i] is the same as writing *(a + i): the array name is the address of the first element, and i is how many elements to move forward from there. With indices starting at 1, every access would compute base + (i - 1) × element_size, or cell 0 would be left unused. Some languages, such as Pascal and Fortran, let you choose the lower bound; the compiler then does this subtraction for you. You will see it in the address questions below.

2Address calculation

In address questions the addresses are given as decimal numbers and each element occupies consecutive bytes. Always follow the same three steps: find how many elements come before the target (the offset), multiply by the element size, then add the base address. The lessons behind this section are two-dimensional arrays and row-major and column-major order.

4In int A[50], an int is 4 bytes and A[0] is at address 2000. a) What are the addresses of A[17] and of the last element? b) An array declared as B[-5..20] with 8-byte elements starts at address 1200. Where is B[7], and how many bytes does the whole array take?Midterm · address calculation

In one dimension the formula is address = base + (i - lower_bound) × element_size. In a C array the lower bound is 0.

  1. a) A[17]: offset 17, address = 2000 + 17 × 4 = 2068.
  2. a) The last element A[49]: address = 2000 + 49 × 4 = 2196. (A[50] is outside the array.)
  3. b) B[7]: offset 7 - (-5) = 12, address = 1200 + 12 × 8 = 1296.
  4. b) Number of elements 20 - (-5) + 1 = 26, total 26 × 8 = 208 bytes.

A common mistake: taking the number of elements as upper bound - lower bound. It is upper - lower + 1; B[-5..20] has 26 elements, not 25.

5In double M[6][9], a double is 8 bytes and M[0][0] is at address 5000. Find the address of M[4][7] in a) row-major order, b) column-major order.Midterm · address calculation

In row-major order the rows are laid out one after another; before M[4][7] come 4 full rows (9 elements each) and 7 elements of row 4. In column-major order the columns are laid out one after another; before it come 7 full columns (6 elements each) and 4 elements of column 7.

Row-majorColumn-major
Formulabase + (i × columns + j) × sbase + (j × rows + i) × s
Offset4 × 9 + 7 = 437 × 6 + 4 = 46
Bytes43 × 8 = 34446 × 8 = 368
Address5000 + 344 = 53445000 + 368 = 5368

In the row-major formula the row index is multiplied by the number of columns; in the column-major formula the column index is multiplied by the number of rows. Mixing these up is the most common mistake here. C and Java are row-major; Fortran and MATLAB are column-major.

6The elements of A[2..8][-3..5] are 4 bytes each and A[2][-3] is at address 1000. Compute the address of A[5][2] in row-major and in column-major order.Final · address calculation

When a lower bound is not 0, subtract each index's own lower bound. First find the dimensions: rows 8 - 2 + 1 = 7, columns 5 - (-3) + 1 = 9.

  1. Row offset: 5 - 2 = 3. Column offset: 2 - (-3) = 5.
  2. Row-major: offset = 3 × 9 + 5 = 32, address = 1000 + 32 × 4 = 1128.
  3. Column-major: offset = 5 × 7 + 3 = 38, address = 1000 + 38 × 4 = 1152.

The general formula, row-major: base + ((i - low1) × columns + (j - low2)) × s. Column-major: base + ((j - low2) × rows + (i - low1)) × s.

7int T[10][12] is stored in row-major order, an int is 4 bytes and T[0][0] is at address 3000. Which element is at address 3260?Midterm · address calculation

This is address calculation in reverse: get the offset from the address, then split the offset into a row and a column.

  1. Byte difference: 3260 - 3000 = 260.
  2. Offset in elements: 260 / 4 = 65.
  3. Row = 65 / 12 = 5 (integer quotient), column = 65 % 12 = 5 (remainder).
  4. Answer: T[5][5]. Check: 3000 + (5 × 12 + 5) × 4 = 3260.

If the byte difference is not a multiple of the element size, that address is not the start of an element; in an exam this tells you the question was misread.

8In short K[4][5][6], a short is 2 bytes and K[0][0][0] is at address 600. Find the address of K[2][3][4] in row-major and in column-major order.Final · address calculation

The same idea works in three dimensions. In row-major order the rightmost index changes fastest; in column-major order the leftmost index changes fastest. The dimensions are d1 = 4, d2 = 5, d3 = 6.

Row-majorColumn-major
Offset formula(i × d2 + j) × d3 + k(k × d2 + j) × d1 + i
Substitute(2 × 5 + 3) × 6 + 4(4 × 5 + 3) × 4 + 2
Offset13 × 6 + 4 = 8223 × 4 + 2 = 94
Address600 + 82 × 2 = 764600 + 94 × 2 = 788

You can also read the row-major result like this: first 2 full layers (5 × 6 = 30 elements each, 60 in total), then 3 full rows (18 elements), then 4 elements. 60 + 18 + 4 = 82.

3Tracing operations

9CAPACITY is 8, the array is [10, 20, 30, 40] and size is 4. These operations run in order: insertAt(pos 1, 15), insertAtFront(5), deleteAt(pos 3), deleteFromEnd(), insertAt(pos 6, 99), deleteFromFront(). Write the array and the size after each one. How many elements are shifted in total?Midterm · tracing

On insertion the element at the position and everything behind it move one place right; on deletion everything behind the deleted position moves one place left. Valid insert positions are 0 to size, valid delete positions are 0 to size - 1.

OperationArraysizeShifted
Start[10, 20, 30, 40]4
insertAt(1, 15)[10, 15, 20, 30, 40]53 (40, 30, 20)
insertAtFront(5)[5, 10, 15, 20, 30, 40]65
deleteAt(3)[5, 10, 15, 30, 40]52 (30, 40)
deleteFromEnd()[5, 10, 15, 30]40
insertAt(6, 99)[5, 10, 15, 30], unchanged40, invalid position (6 > 4)
deleteFromFront()[10, 15, 30]33

Total shifts: 3 + 5 + 2 + 0 + 0 + 3 = 13. In deleteAt(3) the value at position 3 is 20, so 20 is removed. The insert with an invalid position returns false and leaves the array alone.

10Ten elements are appended one by one to a dynamic array with initial capacity 2. When the array is full, its capacity doubles and the old elements are copied into the new block. On which appends does the capacity grow, how many copies are made in total, and how many cells are empty at the end?Midterm · tracing

The array grows only when a new element arrives while it is full. At that moment every element already in it is copied, then the new element is written.

Append numberSize / capacity beforeWhat happensCopies
1, 20/2, 1/2There is room, written0
32/2Capacity becomes 42
54/4Capacity becomes 84
98/8Capacity becomes 168
4, 6, 7, 8, 10There is room, written0

Total copies 2 + 4 + 8 = 14. At the end the size is 10 and the capacity 16, so 6 cells are empty. 10 new writes plus 14 copies make 24 element writes, 2.4 per append. The complexity question below shows why this stays constant as n grows. Growing itself is covered in growing the capacity.

4Code reading

11What does the following code print?Midterm · code reading

The code prints 7 8 9 1 4 3. The loop takes one element from each end of the array, moves towards the middle, and swaps the two when the left one is smaller than the right one.

int a[] = {3, 8, 1, 9, 4, 7};int n = 6;for (int i = 0; i < n / 2; i++) {    if (a[i] < a[n - 1 - i]) {        int temp = a[i];        a[i] = a[n - 1 - i];        a[n - 1 - i] = temp;    }}print(a, n);
iPair comparedSwap?Array
0a[0]=3, a[5]=7Yes, 3 < 77 8 1 9 4 3
1a[1]=8, a[4]=4No7 8 1 9 4 3
2a[2]=1, a[3]=9Yes, 1 < 97 8 9 1 4 3

n / 2 is integer division: 6 / 2 = 3, so i = 0, 1, 2. In each pair the larger value moves left. Without the condition this loop would reverse the array.

12What does mystery return for {4, 12, 7, 9, 3, 6, 1}? What does it compute in general?Final · code reading

The function returns 4. In general it counts the elements that are greater than every element to their right (the last element always counts).

int mystery(int arr[], int size) {    int count = 1;    int best = arr[size - 1];    for (int i = size - 2; i >= 0; i--) {        if (arr[i] > best) {            best = arr[i];            count++;        }    }    return count;}
  1. Start: best = 1 (the last element), count = 1.
  2. i = 5: 6 > 1, best = 6, count = 2.
  3. i = 4: 3 > 6 is false.
  4. i = 3: 9 > 6, best = 9, count = 3.
  5. i = 2: 7 > 9 is false.
  6. i = 1: 12 > 9, best = 12, count = 4.
  7. i = 0: 4 > 12 is false. The result is 4: the counted values are 12, 9, 6 and 1.

The array is walked once from right to left, so the time is and the extra memory O(1). On an empty array arr[size - 1] is an invalid read; pointing this out in an exam earns extra credit.

13A student wrote insertion at a position as below. With the array [1, 2, 3, 4] (size 4, enough capacity), what happens when 9 is inserted at pos 1? Fix the bug.Midterm · code reading

The array becomes [1, 9, 2, 2, 2]; it should have been [1, 9, 2, 3, 4]. The shift runs from the front to the back, so each step writes the value it has just copied into the next cell, and 3 and 4 are lost.

// faulty shiftfor (int i = pos; i < *size; i++)    arr[i + 1] = arr[i];arr[pos] = value;(*size)++;
StepAssignmentArray
i = 1arr[2] = arr[1] = 2[1, 2, 2, 4, _]
i = 2arr[3] = arr[2] = 2[1, 2, 2, 2, _]
i = 3arr[4] = arr[3] = 2[1, 2, 2, 2, 2]
thenarr[1] = 9[1, 9, 2, 2, 2]

The fix: on insertion, shift from the back to the front, for (int i = *size; i > pos; i--) arr[i] = arr[i - 1];. Each element then moves out before it is overwritten. On deletion the direction is the opposite: front to back.

5Code writing

When you write code in an exam, handle the edge cases first: full array, empty array, invalid position. The answers below are in C; the same logic holds in Java and Python.

14Write insertAt(arr, &size, pos, value) and deleteAt(arr, &size, pos). Inserting into a full array, deleting from an empty one and an invalid position should return false.Final · code writing

For insertion pos can be anything from 0 to size (size means appending). Elements shift one place right, from the back to the front, then the new value is written. For deletion pos is from 0 to size - 1, and elements shift one place left, from the front to the back.

bool insertAt(int arr[], int* size, int pos, int value) {    if (*size == CAPACITY) return false;          // array is full    if (pos < 0 || pos > *size) return false;     // invalid position    for (int i = *size; i > pos; i--)        arr[i] = arr[i - 1];                      // shift from the back    arr[pos] = value;    (*size)++;    return true;}
bool deleteAt(int arr[], int* size, int pos) {    if (*size == 0) return false;                  // array is empty    if (pos < 0 || pos >= *size) return false;     // invalid position    for (int i = pos; i < *size - 1; i++)        arr[i] = arr[i + 1];                       // shift from the front    (*size)--;    return true;}

In the worst case (position 0) both shift n elements: . Inserting at and deleting from the end need no shifting: O(1). Step-by-step drawings are in inserting at a position and deleting from the middle.

15Write reverse(arr, size), which reverses an array in place without using a second array.Midterm · code writing

Use two indices: i starts at the front and j at the back. At each step swap the two ends and move both one step towards the middle. Keep going while i < j.

void reverse(int arr[], int size) {    int i = 0, j = size - 1;    while (i < j) {        int temp = arr[i];        arr[i] = arr[j];        arr[j] = temp;        i++;        j--;    }}

It makes n/2 swaps: O(n) time, O(1) extra memory. The condition i <= j would give the same result, but a loop that walks the whole array, like i < size, swaps every pair twice and puts the array back as it was. This comes up often in exams. Details: reversing an array.

16Write a function that finds the largest and the second largest distinct value of an array in a single pass. What should the result be for {7, 3, 9, 9, 5}?Final · code writing

The result should be 9 and 7. Keep two variables, first and second. If a new value is greater than first, the old first becomes second. If it is smaller than first but greater than second, only second changes. A value equal to first is skipped.

bool twoLargest(int arr[], int size, int* first, int* second) {    *first = INT_MIN;    *second = INT_MIN;    for (int i = 0; i < size; i++) {        if (arr[i] > *first) {            *second = *first;        // the old first becomes second            *first = arr[i];        } else if (arr[i] < *first && arr[i] > *second) {            *second = arr[i];        }    }    return *second != INT_MIN;      // false if there is no second distinct value}
Valuefirstsecond
77INT_MIN
373
997
997 (equal, skipped)
597

If you forget the arr[i] < *first condition, second comes out as 9. Time O(n), extra memory O(1). Sorting first and taking the last two also works but takes O(n log n). The code assumes INT_MIN itself is not in the array.

17Write a function that removes repeated values from a sorted array without a second array and returns the new size. What does it return for {2, 2, 3, 5, 5, 5, 8}?Final · code writing

It returns 4, and the front of the array becomes {2, 3, 5, 8}. Because the array is sorted, equal values sit next to each other. k marks the last distinct value written; i scans the array, and when it finds a value different from arr[k] it writes it right after k.

int removeDuplicates(int arr[], int size) {    if (size == 0) return 0;    int k = 0;                      // index of the last distinct value written    for (int i = 1; i < size; i++)        if (arr[i] != arr[k])            arr[++k] = arr[i];      // write the new value right after it    return k + 1;                   // the new size}

Store the new size when you call it: size = removeDuplicates(arr, size);. Each element is read once: O(n), extra memory O(1). Calling deleteAt for each repeat also works, but every deletion shifts the rest, so the worst case is .

18Write a function that rotates an array k steps to the right in O(n) time with O(1) extra memory. What happens to [1, 2, 3, 4, 5, 6, 7] with k = 10?Final · code writing

The result is [5, 6, 7, 1, 2, 3, 4]. Rotating an array of 7 elements by 10 steps is the same as rotating it by 10 % 7 = 3 steps. Three reversals do it: reverse the whole array, then the first k elements, then the rest.

void reverseRange(int arr[], int lo, int hi) {    while (lo < hi) {        int temp = arr[lo];        arr[lo] = arr[hi];        arr[hi] = temp;        lo++;        hi--;    }} void rotateRight(int arr[], int size, int k) {    if (size == 0) return;    k = k % size;                         // rotating by size changes nothing    reverseRange(arr, 0, size - 1);       // 1. reverse everything    reverseRange(arr, 0, k - 1);          // 2. reverse the first k elements    reverseRange(arr, k, size - 1);       // 3. reverse the rest}
  1. Reverse everything: [7, 6, 5, 4, 3, 2, 1].
  2. Reverse the first 3 elements: [5, 6, 7, 4, 3, 2, 1].
  3. Reverse the remaining 4 elements: [5, 6, 7, 1, 2, 3, 4].

Each element moves at most twice: O(n). Shifting the array one step k times takes O(n × k), and copying into a second array needs O(n) extra memory. To rotate left, change the order of the reversals: first the first k, then the rest, and the whole array last.

19Write a function that merges the sorted arrays a (n elements) and b (m elements) into one sorted array c. Show the steps for a = {1, 4, 9, 12}, b = {2, 3, 10}.Final · code writing

Put an index at the front of each array. At each step write the smaller of the two front values into c and advance that index. When one array runs out, append the rest of the other one as it is.

int merge(int a[], int n, int b[], int m, int c[]) {    int i = 0, j = 0, k = 0;    while (i < n && j < m) {        if (a[i] <= b[j]) c[k++] = a[i++];   // take the smaller one        else              c[k++] = b[j++];    }    while (i < n) c[k++] = a[i++];          // what is left in a    while (j < m) c[k++] = b[j++];          // what is left in b    return k;                               // size of c: n + m}
a[i]b[j]Written to cc
1211
4221 2
4331 2 3
41041 2 3 4
91091 2 3 4 9
1210101 2 3 4 9 10
12done12 (rest)1 2 3 4 9 10 12

Each element is written once: O(n + m) time and O(n + m) memory for c. Using <= takes the value from a first when two values are equal; this is the detail that makes merge sort stable.

20Write a function that moves all zeros of an array to the end without changing the order of the other elements. What does {0, 5, 0, 0, 3, 8, 0, 1} become?Midterm · code writing

The result is {5, 3, 8, 1, 0, 0, 0, 0}. k holds the place where the next non-zero value goes. The array is scanned once, the non-zero values are written to the front in order, and the remaining cells are filled with zeros.

void moveZerosToEnd(int arr[], int size) {    int k = 0;                       // where the next non-zero value goes    for (int i = 0; i < size; i++)        if (arr[i] != 0)            arr[k++] = arr[i];    while (k < size)        arr[k++] = 0;                // fill the remaining cells with zeros}

Time O(n), extra memory O(1). The non-zero values are written in the order they are found, so their relative order is kept. Deleting each zero and appending it at the end also works, but takes .

6Complexity and comparison

21Give the worst-case time complexity of the operations below on an unsorted, fixed-capacity array of n elements, with a reason for each.Final · complexity

The rule is simple: if the operation shifts elements or scans the array it is O(n); if it only computes an address it is O(1).

OperationWorst caseReason
Read or write by indexO(1)The address is computed by a formula
Insert at the end (if there is room)O(1)No shifting
Insert at the frontO(n)n elements shift right
Insert at a positionO(n)size - pos elements shift
Delete from the endO(1)Only the size decreases
Delete from the frontO(n)n - 1 elements shift left
Delete from the middleO(n)The rest shifts left
Search for a valueO(n)Every element may be checked; binary search is O(log n) if sorted
ReverseO(n)n/2 swaps

A follow-up question is common: on average, how many elements shift when you insert at a random position? If each position from 0 to n is equally likely, the shifts are n, n - 1, ..., 0; the average is n/2. Constant factors drop, so this is still O(n).

22What would change if a dynamic array grew by 10 cells instead of doubling when full? Append 1000 elements to an array with initial capacity 10, compare the total number of copies for the two methods, and find the average cost of an append.Final · complexity

With doubling, 1000 appends make 1270 copies in total; growing by 10 makes 49,500. With doubling an append costs O(1) on average (amortized); with a fixed increase it costs O(n) on average.

DoublingGrowing by 10
Sizes at which it grows10, 20, 40, 80, 160, 320, 64010, 20, 30, ..., 990
Number of grows799
Total copies10 + 20 + ... + 640 = 127010 × (1 + 2 + ... + 99) = 49,500
Final capacity12801000
  1. With doubling the copies form a geometric series. Each term is twice the one before, so the total is less than twice the last term: 1270 < 2 × 640. The last term is smaller than n, so the total number of copies is below 2n.
  2. n appends do at most n writes + 2n copies = 3n work. That is 3 units per append on average, so O(1). Looked at one by one, the append that triggers a grow takes O(n), but these expensive steps are rare.
  3. Growing by 10 happens every 10 appends, and the amount copied gets larger each time. The total is about n²/20, which is ; on average O(n) per append.

The price of doubling is unused capacity: with 1000 elements, 280 cells sit empty. Still, multiplying the capacity by a constant factor (1.5 or 2) at each grow is what keeps appends fast. Details in growing the capacity.

7Try it

int X[5][8] is stored in row-major order, an int is 4 bytes and X[0][0] is at address 100. Where is X[3][2]?

Show the answer

The answer is C. The offset is 3 × 8 + 2 = 26, so the address is 100 + 26 × 4 = 204. 152 is the column-major result: (2 × 5 + 3) × 4 + 100. 168 comes from multiplying the row index by the number of rows instead of columns: (3 × 5 + 2) × 4 + 100.

In a dynamic array that doubles its capacity when full, what is the amortized complexity of appending?

Show the answer

The answer is A. A single grow takes O(n), but grows are so rare that n appends never make more than 2n copies. Each append gets a constant amount of work on average.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.