AxoPrep

Computer Science

B2.2 Data structures

Watch the lesson2D Arrays in Java: Rows & Columns

Storing collections in arrays and lists, using one- and two-dimensional structures, choosing the right structure, and (HL) stacks and queues. Study guide, 5 practice questions with markschemes and 4 flashcards. Free.

static arrays and dynamic lists · one- and two-dimensional structures · choosing a suitable structure · (HL) stacks · (HL) queues

Practise all 5 questions Study 4 flashcards ▶ Watch the video lesson

Study guide

Static arrays and dynamic lists

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
names.add("Ana");
names.add("Kofi");
names.remove(0);          // names is now [Kofi]
int n = names.size();     // 1

Indexes start at 0, so the last item of a list of length n is at n - 1.

One-dimensional processing

The standard patterns are total, count, maximum/minimum and search:

temps = [18, 23, 21, 27, 19]
highest = temps[0]           # start from a real item, not 0
for t in temps:
    if t > highest:
        highest = t
print(highest)               # 27

Starting the maximum at temps[0] (rather than 0) keeps the code correct when every value is negative.

Two-dimensional structures

A 2D structure is a list of rows; grid[r][c] is row r, column c.

marks = [[7, 5, 6],
         [4, 6, 3],
         [6, 7, 5]]

marks[1][2] is 3 (row 1, column 2). To process every cell, nest two loops: outer over rows, inner over columns.

# total of each column
cols = len(marks[0])
for c in range(cols):
    total = 0
    for r in range(len(marks)):
        total = total + marks[r][c]
    print(c, total)

Output: 0 17, 1 18, 2 14. The main diagonal is marks[i][i] (7, 6, 5); the other diagonal is marks[i][n-1-i] (6, 6, 6).

Java uses the same idea: int[][] seats = new int[12][30];, then seats.length is the number of rows and seats[0].length the number of columns.

Choosing a structure

SituationBest fitWhy
Size known and fixed (chessboard, 7 days)Static arrayFast, memory-efficient, size never changes
Size unknown or changing (online queue, chat log)Dynamic listCan grow and shrink
Grid or table data (seating, pixels, timetable)2D arrayNatural row/column indexing
Undo history, matching bracketsStack (HL)Last in, first out
Print jobs, customer service lineQueue (HL)First in, first out

Stacks (HL)

A stack is LIFO: the last item pushed is the first popped. Operations: push, pop, peek (look at the top), isEmpty.

Trace: push 3, push 8, pop, push 1, pop, pop.

OperationStack (bottom -> top)Returned
push 33
push 83, 8
pop38
push 13, 1
pop31
popempty3

Uses: undo, browser back button, the call stack for functions, checking balanced brackets (push every opening bracket, pop on each closing one and check they match; the expression is balanced only if the stack is empty at the end). Popping an empty stack is underflow; pushing onto a full fixed-size stack is overflow.

Queues (HL)

A queue is FIFO: items join at the rear (enqueue) and leave from the front (dequeue).

from collections import deque
q = deque()
q.append("job1")      # enqueue
q.append("job2")
first = q.popleft()   # dequeue -> "job1"

A circular queue in a fixed array wraps the front and rear pointers back to index 0, so freed space is reused: rear = (rear + 1) % size.

Common mistakes

Exam tips

Cheat sheet

StructureSizeAccessOrder
Static arrayfixedby index, O(1)positional
Dynamic listchangesby index, O(1); insert at front O(n)positional
Stack (HL)changestop onlyLIFO
Queue (HL)changesfront and rearFIFO

Key definitions

Static array

A fixed-size collection of same-type items stored in consecutive memory and accessed by index.

Dynamic list

A collection whose size can change at run time as items are added or removed.

Index

The position number used to access an item in an array or list, starting from 0 in Python and Java.

Two-dimensional array

An array of arrays, accessed with a row index and a column index.

Stack (HL)

A last-in, first-out structure where items are added and removed only at the top.

Queue (HL)

A first-in, first-out structure where items join at the rear and leave from the front.

Underflow (HL)

An error caused by trying to remove an item from an empty stack or queue.

Circular queue (HL)

A queue in a fixed-size array whose pointers wrap round to the start, reusing freed positions.

Practice questions

SLPaper 2Standard

Question 1

(a) [2]

Consider the 2D list:

grid = [[3, 8, 1],
        [6, 2, 9],
        [4, 7, 5]]

State the values of grid[1][2] and grid[2][0].

Markscheme
  • 1 grid[1][2] = 9
  • 1 grid[2][0] = 4
(b) [3]

State the output of the following code.

a = 0
b = 0
for i in range(3):
    a = a + grid[i][i]
    b = b + grid[i][2 - i]
print(a, b)
Markscheme
  • 1 a = 3 + 2 + 5 = 10
  • 1 b = 1 + 2 + 4 = 7
  • 1 Output: 10 7
SLPaper 2Challenging

Question 2

(a) [5]

A shop chain stores daily sales in a 2D list sales, where each row is one store and each column one day of the week. For example:

sales = [[120, 95, 130, 80, 150, 200, 170],
         [ 60, 75,  90, 85, 100, 140, 110],
         [200, 180, 210, 190, 230, 260, 240]]

Construct a Python function grand_total(sales) that returns the total of all sales in the list. It must work for any number of stores and days.

Markscheme
  • 1 Initialises a total to 0
  • 1 Correct loop over rows
  • 1 Correct nested loop over columns (using the length of each row, not a fixed 7)
  • 1 Accumulates total correctly
  • 1 Returns result
(b) [4]

Construct a function best_store(sales) that returns the row index of the store with the highest weekly total.

Markscheme
  • 1 Calculates a total for each row
  • 1 Keeps track of the highest total found so far
  • 1 Updates the stored index when a larger total is found
  • 1 Returns the index (not the total)
SLPaper 2Very hard

Question 3

(a) [5]

Construct a Java method public static int[] columnMax(int[][] data) that returns an array containing the largest value in each column of data. Assume every row has the same length and there is at least one row.

Markscheme
  • 1 Creates a result array with length equal to the number of columns (data[0].length)
  • 1 Outer loop over columns
  • 1 Initialises the maximum to the first value in that column (not 0)
  • 1 Inner loop over rows, comparing and updating the maximum
  • 1 Stores each column's maximum and returns the array
(b) [2]

Explain why initialising the maximum to 0 could give a wrong result.

Markscheme
  • 1 If every value in a column is negative
  • 1 0 would be returned, which is not in the column

Key facts

Indexing a 2D list: grid[r][c]

First index = row, second index = column; both start at 0.

Looping over every cell of a 2D list

Outer loop over rows (len(grid)), nested inner loop over columns (len(grid[r])).

Static array vs dynamic list

Static array: fixed size, set at creation. Dynamic list: can grow and shrink at run time.

(HL) Stack vs queue

Stack: LIFO, push/pop at the top. Queue: FIFO, enqueue at the back, dequeue from the front.