KatInterview

Simulate Slice Appending in Go

Arrays & HashingAuto-graded · 16 test cases
EasyAuto-gradedArrays & Hashingarrayssimulation

Last updated

Simulate how slicing and slice appending mutate backing arrays and slice headers in Go.

In the Go programming language, a slice is represented by a header containing a pointer to an underlying backing array, a length, and a capacity.

When a slice y is created by slicing an existing slice x from index 0 up to prefix_len (i.e. y = x[:prefix_len]), y shares x's backing array. The initial length of y is prefix_len, and its capacity equals the total length of x (assuming x starts at index 0).

When append(y, len(y)) is called inside a helper function:

  1. It calculates the value to append, which is len(y).
  2. If y has spare capacity (that is, if len(y) < cap(y)), Go writes the appended value directly into the backing array at index len(y) (which updates the shared memory visible in x). The function returns a new slice header z referencing the same backing array with length len(y) + 1.
  3. If y has no spare capacity (that is, len(y) == cap(y)), Go allocates a new separate backing array, copies the contents of y, appends the value, and returns a slice header z pointing to this new array. x remains unaffected.

Given an initial list of integers backing representing slice x and an integer prefix_len representing the sub-slice length for y, simulate the execution of the following Go code:

x := backing
y := x[:prefix_len]
z := append(y, len(y))
fmt.Println(x)
fmt.Println(y)
fmt.Println(z)

Return a list of 3 strings corresponding to the output printed by fmt.Println(x), fmt.Println(y), and fmt.Println(z). Go's fmt.Println formats a slice as space-separated values enclosed in square brackets (e.g., "[1 2 3 3 0 0 0]").

Constraints

  • 1 <= len(backing) <= 1000
  • 0 <= prefix_len <= len(backing)
  • 0 <= backing[i] <= 1000

Examples

Example 1

Input: append_to_subslice_output([1, 2, 3, 0, 0, 0, 0], 3)

Output: ['[1 2 3 3 0 0 0]', '[1 2 3]', '[1 2 3 3]']

Hints

Hint 1

Check whether `prefix_len < len(backing)`. If so, appending to `y` overwrites `backing[prefix_len]`.

Hint 2

The slice `y` itself never changes its length header, so its printed representation remains `backing[:prefix_len]`.

Hint 3

Format each list by placing elements inside square brackets separated by single spaces.