Simulate Slice Appending in Go
Arrays & HashingAuto-graded · 16 test casesLast 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:
- It calculates the value to append, which is
len(y). - If
yhas spare capacity (that is, iflen(y) < cap(y)), Go writes the appended value directly into the backing array at indexlen(y)(which updates the shared memory visible inx). The function returns a new slice headerzreferencing the same backing array with lengthlen(y) + 1. - If
yhas no spare capacity (that is,len(y) == cap(y)), Go allocates a new separate backing array, copies the contents ofy, appends the value, and returns a slice headerzpointing to this new array.xremains 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) <= 10000 <= 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To solve this problem, we simulate Go's slice semantics directly in Python:
- Backing Array & Slice
x:xbegins as a copy ofbacking. - Sub-slice
y:yconsists of the firstprefix_lenelements ofx. The length ofyisprefix_len, and its capacity islen(x). - Appending: The value to append is
len(y), which equalsprefix_len.- If
prefix_len < len(x),yhas spare capacity. Go writes the appended value directly into indexprefix_lenof the backing array shared withx. Thus,x[prefix_len]is mutated toprefix_len. - If
prefix_len == len(x),yhas no remaining capacity. Go allocates a new array forz, leavingxunmodified.
- If
- Slice
z:zcontains the elements ofyfollowed bylen(y). - Formatting: Each slice is converted into Go's standard string representation:
"[v1 v2 ... vn]".
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of elements in
backing, required to slice, copy, and string-format the slices. - Space Complexity: $\mathcal{O}(N)$ auxiliary space to store the slice representations and formatted output strings.
Python Reference Solution
from typing import List
def append_to_subslice_output(backing: List[int], prefix_len: int) -> List[str]:
x = backing[:]
y = x[:prefix_len]
appended_value = len(y)
# y has capacity len(x). If it has spare capacity, append writes into
# x's backing array; otherwise Go allocates a new backing array.
if prefix_len < len(x):
x[prefix_len] = appended_value
z = y + [appended_value]
def go_slice(values: List[int]) -> str:
return "[" + " ".join(str(value) for value in values) + "]"
return [go_slice(x), go_slice(y), go_slice(z)]