Coding interviews
Reveal answer and reasoning
The word character is ambiguous in a .NET interview. A string length counts UTF-16 code units; Rune enumeration counts Unicode scalar values; StringInfo identifies text elements. This task truncates by the latter unit so it does not split the sample emoji surrogate pair or the combining sequence. It preserves the original spelling and does not normalize equivalent sequences. Ask whether the product measures code units, scalar values, grapheme-like text elements or rendered columns.
These quantities can disagree even for a short valid string. The task deliberately chooses text elements for truncation and preserves original spelling, leaving normalization and display layout as independent policies.
Parsing all element boundaries takes O(n) work and O(g) index storage for g text elements. The substring result can allocate O(n) code units. This implementation prioritizes a clear boundary contract rather than a minimal-allocation prefix scan. Unicode segmentation behavior follows the runtime implementation. The boundary-array approach allocates proportional to the number of elements even when only a short prefix is requested.
A streaming text-element enumerator could reduce retained boundary storage, but the simpler implementation is easier to audit. Choose the alternative only after preserving the same semantics and verifying the required runtime behavior.
What a strong answer covers
- The word character is ambiguous in a .NET interview.
- The element-start array identifies A at zero, the emoji at one and the combining sequence at three.
- Parsing all element boundaries takes O(n) work and O(g) index storage for g text elements.
Common pitfall
Rune is not the same as a user-perceived grapheme, and string.Length is not a display width. Equal-looking strings can still differ ordinally without normalization. Input containing unpaired surrogates or requirements for locale-specific presentation need an explicit policy beyond this fixed valid-Unicode fixture.
Follow-up questions
- Test count zero, a count beyond the element count and precomposed versus decomposed accented text. Hint: compare both preserved code units and element counts rather than assuming normalization occurred.
- How can normalization invalidate offsets that were measured in the original spelling?
Self-review
Choose what to revisit. These marks are your own assessment and are separate from lesson completion.