Field Layout: getOffset and insert
Jane StreetFrontend Engineer · Technical ScreenLast updated
This question evaluates a candidate's ability to model and maintain ordered field layouts by computing and updating byte offsets, testing competencies in dynamic sequence data structures, cumulative offset tracking, and efficient update/query operations.
An object's binary layout is defined by an ordered list of fields. Each field has a unique name and a size in bytes. Fields are packed contiguously starting at byte offset 0, in list order: the first field starts at offset 0, and each subsequent field starts where the previous one ends.
For example, the field list (foo, 3), (bar, 6), (baz, 2) produces this layout:
| Field | Size (bytes) | Occupies byte range |
|---|---|---|
foo | 3 | [0, 3) |
bar | 6 | [3, 9) |
baz | 2 | [9, 11) |
Implement a class FieldLayout that supports the following operations:
FieldLayout(fields)— initialize the layout from a list of(name, size)pairs, in order.getOffset(name)— return the starting byte offset of the fieldname.insert(name, size, index)— insert a new field with the given name and size at positionindexin the field order (0-based; this is a position in the list of fields, not a byte offset). All fields at positionindexand later shift toward the end, and their byte offsets increase bysize.
Example
Starting from (foo, 3), (bar, 6), (baz, 2):
getOffset("bar") -> 3
insert("qux", 2, 1) -> layout becomes foo[0,3), qux[3,5), bar[5,11), baz[11,13)
getOffset("bar") -> 5
getOffset("baz") -> 11
insert("end", 4, 4) -> appended at the end: end[13,17)
getOffset("end") -> 13
getOffset("foo") -> 0
Constraints
1 <= initial number of fields <= 10^51 <= total number of getOffset and insert calls <= 10^51 <= size <= 10^4for every field- Field names are unique non-empty strings;
getOffsetis only called with the name of a field that exists in the layout. - For every
insert,0 <= index <= current number of fields(inserting atindex == current number of fieldsappends to the end). - Offsets fit in a 64-bit integer.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.