HTTP API Design for Binomial Coefficient Sequences
System DesignModel answerLast updated
Design a clean HTTP API that delivers row-by-row binomial coefficients, covering endpoint structure, validation, error contracts, and numeric limits.
You're designing a public HTTP API that serves sequences of binomial coefficients arranged in triangular form (each row n contains the coefficients C(n, 0) through C(n, n)).
The service should return structured numeric data only—no formatting, padding, or visual layout. Clients are responsible for rendering and presentation.
Specify:
- Endpoint design – HTTP method, path, and parameters
- Response schema – JSON structure with concrete examples
- Validation rules – parameter types, ranges, and rejection criteria
- Error handling – status codes, error envelope format, and specific error cases
- Practical constraints – maximum input size with technical justification (consider both client numeric precision and server resource limits)
- Non-functional concerns – caching, rate limiting, and any other production-readiness considerations
Provide a model answer that demonstrates systematic API design thinking, grounded in HTTP semantics and real-world numeric constraints.
Hints
Hint 1
Consider which HTTP method best reflects the operation's semantics—does it mutate state or compute a pure function of its input?
Hint 2
JSON numbers have precision limits in many clients; calculate exactly where IEEE-754 double precision breaks down for the largest coefficient in each row.
Hint 3
Edge cases matter: how should the API handle zero rows, malformed integers, or parameters just beyond the numeric safety boundary?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: HTTP API for Binomial Coefficient Sequences
This problem tests your ability to design a clean, production-grade HTTP interface with careful attention to contracts, validation, and real-world numeric limits.
1. Endpoint Design
Recommended:
GET /v1/triangle?rows=5
Key decisions:
-
GET with query parameter. This operation is a pure, stateless function with no side effects—perfect for GET. It's inherently idempotent and cacheable. Alternative:
/v1/triangle/5as a path parameter also works; query parameters offer more flexibility for future optional parameters. -
Plural parameter name
rows. Clear intent: you're requesting n rows of output. -
API versioning (
/v1). Future-proofs the contract. If you later need to change numeric encoding (e.g., strings for arbitrary precision), you can ship/v2without breaking existing clients.
2. Response Schema
Return structured JSON with row-wise arrays:
{
"rows": 5,
"data": [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]
]
}
Design rationale:
- Nested integer arrays. Each sub-array is one row. Clients parse raw numbers and handle their own layout, fonts, and alignment.
- Echo the input (
"rows": 5). Makes responses self-documenting and aids debugging. - No string padding or formatting. Returning
" 1 2 1 "would couple the server to one presentation style.
3. Validation Rules
| Parameter | Type | Constraint | Error on Violation |
|---|---|---|---|
rows | integer | required | 400 if missing |
rows | integer | 0 ≤ rows ≤ 57 | 400 if out of range |
rows | integer | base-10, no decimals | 400 if malformed |
Specific rules:
- Missing
rows: Return400with codeMISSING_PARAMETER. Don't silently default—explicit contracts prevent confusion. - Non-integer input (
3.14,abc,1e5, empty string):400with codeINVALID_INTEGER. - Negative values:
400with codeOUT_OF_RANGE. rows=0: Return200with"data": []. Zero rows is a valid, meaningful result.- Multiple
rowsparameters (?rows=3&rows=5): Reject with400. - Unknown query parameters: Either ignore (lenient) or reject with
400(strict, catches typos like?rowss=5). Document your choice.
4. Practical Constraints: Why 57?
Two independent limits apply:
A. Client Numeric Precision
JSON parsers in JavaScript, Python's json module, and most languages use IEEE-754 double-precision floats. Integers are exact only up to 2^53 − 1 ≈ 9.007 × 10^15.
The largest coefficient in row n (zero-indexed) is C(n, ⌊n/2⌋):
- C(56, 28) ≈ 7.65 × 10^15 → safe
- C(57, 28) ≈ 1.45 × 10^16 → exceeds safe integer range
A triangle with 57 rows includes rows 0 through 56. Therefore, 57 rows is the maximum where every coefficient is exactly representable in standard JSON clients. Beyond that, browsers and other tools silently produce incorrect values—worse than an error.
B. Payload Size
At 57 rows: 57×58/2 = 1,653 numbers ≈ 20 KB of JSON—trivial for both server and client.
Extension for larger triangles: If needed, add an opt-in ?format=string parameter that encodes coefficients as decimal strings. Cap this mode at ~200 rows (≈20,000 entries, ~700 KB). Without a cap, unbounded requests enable denial-of-service attacks.
5. Error Handling
Use a consistent error envelope:
{
"error": {
"code": "OUT_OF_RANGE",
"message": "rows must be between 0 and 57",
"details": {
"parameter": "rows",
"min": 0,
"max": 57,
"received": 100
}
}
}
Status Code Map
| Code | Scenario | Error Code Example |
|---|---|---|
200 | Valid request | — |
400 | Missing, malformed, or out-of-range input | MISSING_PARAMETER, INVALID_INTEGER, OUT_OF_RANGE |
405 | Non-GET method | Include Allow: GET header |
429 | Rate limit exceeded | Include Retry-After header |
500 | Unexpected server failure | Generic message; log internally, never leak stack traces |
Machine-readable codes let clients branch on stable identifiers, not fragile message strings.
6. Non-Functional Concerns
Caching
Responses are immutable for a given input:
Cache-Control: public, max-age=31536000, immutable
ETag: "triangle-57"
You can precompute all 58 responses at startup and serve them from memory or a CDN.
Rate Limiting
Cap per-client requests (e.g., 100/minute) to prevent abuse. Return 429 with Retry-After: 60 when exceeded.
CORS
If browsers will call this API, include appropriate Access-Control-Allow-Origin headers.
7. Edge Cases Checklist
rows=0→200with emptydataarrayrows=1→[[1]]rows=57→ accepted;rows=58→400with limit in error details- Very large digit strings (
rows=99999999999999999999) → must fail cleanly with range error, not crash or hang - Malformed input (
3.0," 5 ", trailing characters) → consistent400behavior
8. Complexity & Implementation Notes
Time: O(n²) to generate n rows (one addition per coefficient).
Space: O(n²) for the response payload.
At n ≤ 57, both are negligible, making precomputation viable.
Generation algorithm: Each row is computed from the previous using C(n, k) = C(n−1, k−1) + C(n−1, k), with 1s on both edges. Server-side integers (Python int, Java BigInteger) never overflow; the cap exists purely for clients.
Common Mistakes to Avoid
- Defaulting missing
rowsto 10. Explicit failures are clearer than magic defaults. - Rejecting
rows=0. Zero is a valid mathematical case. - Ignoring IEEE-754 limits. Clients silently corrupt large numbers—better to enforce a cap.
- Inconsistent error formats. Every error should follow the same JSON schema.
- Using POST. This is a read-only, cacheable query—GET is semantically correct.
This design balances simplicity, correctness, and production-readiness, demonstrating systematic thinking about HTTP semantics, numeric precision, validation, and operational concerns.