Real Interview Questions for the Software Engineer at Leonardo
NewInterview Q&A
Q&A-1Find the longest substring without repeating characters, and how would you handle streaming input?
Reported in Leonardo Graduate Software Engineer Interview Questions & Prep Guide 2026 | InterviewSense
The 90-second answer
For a finite string, use a sliding window with the last index of each character. Keep left at the start of the current window with no repeats, move right across the string, and whenever s[right] was last seen at or after left, move left to one past that occurrence. The window s[left:right+1] is then the longest repeat-free substring ending at right. Track its length and start. That is O(n) time and O(min(n, alphabet)) space.
For streaming input, the same state works incrementally, but you cannot return a final answer until the stream ends. You maintain the window, the last-seen map, and the best window found so far, and you emit an update only when the best improves. The catch is memory: if the stream is genuinely unbounded and keeps producing new characters, the exact window can grow without bound.
# Python 3.12, iterates Unicode code points, not UTF-8 bytes
def longest_unique(s: str) -> tuple[int, str]:
last: dict[str, int] = {}
left = best_len = best_start = 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1
last[ch] = right
if right - left + 1 > best_len:
best_len, best_start = right - left + 1, left
return best_len, s[best_start:best_start + best_len]
longest_unique("abcaab") # (3, 'abc')Worked trace for abcaab. The invariant is that left never moves backwards, which is why this is linear rather than quadratic.
| right | ch | last[ch] before | left after | window | best |
|---|---|---|---|---|---|
| 0 | a | - | 0 | a | a |
| 1 | b | - | 0 | ab | ab |
| 2 | c | - | 0 | abc | abc |
| 3 | a | 0 | 1 | bca | abc |
| 4 | a | 3 | 4 | b | abc |
| 5 | b | 1 | 4 | ab | abc |
Streaming: what changes and what does not
The window logic does not change. What changes is the contract around it.
Three details decide whether the streaming version is correct.
First, decode before you window. A chunk boundary can split a multi-byte UTF-8 sequence or a surrogate pair in UTF-16. Windowing raw bytes would treat the two halves of one character as two different characters and could report a window that splits a character. Use an incremental decoder and feed it whole code points. If the product cares about grapheme clusters (for example, e plus a combining accent) rather than code points, say so explicitly, because the answer differs.
Second, decide what "longest so far" means when the window is unbounded. With bytes the window is capped at 256 distinct values, so memory is bounded. With Unicode code points it is not. A telemetry or log stream that emits mostly unique identifiers will grow the window and the last-seen map indefinitely. The exact answer requires that retention. If memory is capped, you must change the question: keep a bounded window of size k, or reset after emitting a candidate, and label the result as the longest within that bound rather than the longest overall. Resetting silently is the common bug here, because it discards a window that crosses the reset point.
Third, emit sparingly. Updating a downstream consumer on every character is O(n) messages for a result that changes rarely. Emit only when best_len increases, and include the window start offset in the stream so the consumer can locate it without retaining the whole input.
| Concern | Batch | Streaming |
|---|---|---|
| Answer available | At the end, in one pass | Provisional, improves over time |
| Memory | O(window) | O(window), unbounded if input is |
| Chunk boundaries | None | Must decode incrementally |
| Output | One substring | Updates only on improvement |
Failure modes worth naming: using byte indices against a decoded string, so offsets drift after the first multi-byte character; storing the last-seen index but comparing it against 0 instead of left, which lets left move backwards; and assuming the stream ends, so the final best is never flushed when the producer closes without an explicit end-of-stream signal.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Group anagrams from a list of strings, and discuss the complexity trade-offs of your approach?
Reported in Leonardo Software Engineer Interview Questions & Prep Guide 2026 | InterviewSense
The 90-second answer
I would group by a canonical signature for each string and store the signature as a hash map key, with the list of original strings as the value. For a general interview answer I would start with sorting each string, because it is correct for any alphabet and easy to defend. If the strings are long, or the alphabet is known to be small, I would switch the signature to a character count, because that removes the log factor per string.
Assume n strings, average length L, and alphabet size sigma. Sorting costs O(n * L log L) time. Counting costs O(n * L) time to build the count, plus O(sigma) if the count is stored as a dense tuple. Both need O(n * L) space in the worst case if I keep every signature and every original string, though the count version can use less extra space when sigma is small.
Worked trace
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
| String | Sorted signature | Count signature for a-z | Group |
|---|---|---|---|
| eat | aet | (1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0) | eat, tea, ate |
| tea | aet | same as eat | eat, tea, ate |
| tan | ant | (1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0) | tan, nat |
| ate | aet | same as eat | eat, tea, ate |
| nat | ant | same as tan | tan, nat |
| bat | abt | (1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) | bat |
Result: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]. Order inside a group follows input order if I append as I scan, which is usually what callers expect.
Code, checked against Python 3.12
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
groups: dict[tuple[int, ...], list[str]] = defaultdict(list)
for s in strs:
count = [0] * 26
for ch in s:
if not ("a" <= ch <= "z"):
# Fall back for input outside the assumed alphabet.
return _group_by_sorting(strs)
count[ord(ch) - 97] += 1
groups[tuple(count)].append(s)
return list(groups.values())
def _group_by_sorting(strs: list[str]) -> list[list[str]]:
groups: dict[str, list[str]] = defaultdict(list)
for s in strs:
groups["".join(sorted(s))].append(s)
return list(groups.values())The fallback matters. A count tuple hard coded to 26 letters silently breaks on uppercase, digits, punctuation or Unicode. Sorting has no alphabet assumption, so it is the safer default when the input contract is unclear.
Trade-offs in numbers
Take n = 1,000,000 strings of length L = 10. Sorting does roughly 1,000,000 * 10 * log2(10), about 33 million comparisons, plus allocation of a new 10 character string per input. Counting does about 10 million increments and builds a 26 element tuple per input. In CPython the tuple allocation often dominates, so counting is not automatically faster in practice for short strings. For L = 1,000, sorting does about 1,000,000 * 1,000 * 10 comparisons, roughly 10 billion, while counting stays near 1 billion increments. That crossover is why I would ask about expected length before committing.
| Approach | Time | Extra space per string | Alphabet assumption | Main risk |
|---|---|---|---|---|
| Sort each string | O(n * L log L) | O(L) for the sorted copy | None | Slow on long strings, many allocations |
| Count tuple, dense | O(n * L + n * sigma) | O(sigma) for the tuple | Fixed alphabet, e.g. 26 or 256 | Breaks or bloats on Unicode, tuple hashing cost |
| Count dict, sparse | O(n * L) average | O(k) where k is distinct chars in the string | None | Hash overhead per character, worst case still correct |
| Incremental hash, e.g. product of primes | O(n * L) | O(1) | None | Collisions group non-anagrams, overflow in fixed width languages |
Failure modes I would name in the loop
Empty strings all land in one group, which is correct, but callers sometimes expect them filtered. Case and whitespace change the answer: "Tea" and "eat" are not anagrams under a strict definition, and "a b" differs from "ab". If the product definition ignores case or spaces, I would normalize before signing and say so explicitly, because normalization can also merge strings the caller wanted apart. Unicode adds a subtler trap: "é" as a single code point and as e plus a combining accent look identical but have different code points, so sorting or counting raw code points puts them in different groups. That is a spec question, not a coding bug, and I would surface it rather than guess.
Memory is the other failure mode. Storing both the signature map and the original strings doubles retention for large inputs. If the input is a stream too large to hold, I would need an external sort or a two pass approach with the signature written to disk, and I would state that the in memory hash map assumes the whole list fits. Hash collisions in the map itself are handled by Python dict equality on the full tuple or sorted string, so correctness does not depend on hash quality. That is the reason I would avoid a single integer hash as the key unless I add a verification step.
If pressed to pick one for production code with unknown input, I would ship the sorting version first, add tests for empty input, single characters, duplicates and non lowercase input, then switch to counting only after profiling shows long strings dominate. That order keeps the first version correct while the data tells me whether the faster signature is worth the extra assumption.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Perform a binary tree post-order traversal iteratively without recursion?
Reported in Leonardo Graduate Software Engineer Interview Questions & Prep Guide 2026 | InterviewSense
The 90-second answer
Post-order is left, right, root. The iterative version I would write first uses two stacks in effect, by doing a root, right, left walk and reversing it. That gives left, right, root without recursion and without tracking visited state.
# Python 3.12
def postorder(root):
if root is None:
return []
out = []
stack = [root]
while stack:
node = stack.pop()
out.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return out[::-1]Push left before right so right is popped first. The collected order is root, right, left. Reversing it yields left, right, root. Time is O(n) because each node is pushed and popped once. Extra space is O(n) in the worst case for a skewed tree, O(h) on average where h is height, plus O(n) for the output list.
Worked trace
Tree: 1 with left 2 and right 3; 2 with left 4 and right 5.
| Step | Pop | Append to out | Push left, then right | Stack after |
|---|---|---|---|---|
| 1 | 1 | 1 | 2, 3 | [2, 3] |
| 2 | 3 | 1, 3 | none | [2] |
| 3 | 2 | 1, 3, 2 | 4, 5 | [4, 5] |
| 4 | 5 | 1, 3, 2, 5 | none | [4] |
| 5 | 4 | 1, 3, 2, 5, 4 | none | [] |
Reversed output: [4, 5, 2, 3, 1], which is the required post-order.
The one-stack alternative
Interviewers often ask for a single stack. That version descends to the leftmost node, then climbs back, emitting a node only after its right child is done or absent. It needs a last_visited pointer to know whether the right subtree was already processed. It uses the same O(n) time and O(h) auxiliary space, but the state machine is easier to get wrong under follow-up questions about a node with only a right child. I would present the reverse-preorder version first because the invariant is visible in the code, then mention the one-stack version if space for the reversed output matters.
| Approach | Auxiliary space | Output | Main risk |
|---|---|---|---|
| Reverse preorder | O(n) worst case | Built reversed, then flipped in place | Extra list if memory is tight |
| One stack plus last visited | O(h) | Emitted in final order | Bug when right child is missing or already visited |
| Recursion | O(h) call stack | Emitted in final order | Recursion limit or C stack overflow on deep trees |
Failure modes to name
A degenerate tree with 100,000 nodes in a chain will overflow the default Python recursion limit of 1,000 and can overflow the C stack in languages with a fixed call stack. The iterative version moves that storage to the heap, so it survives, but the stack list still grows to 100,000 entries. If the caller only needs the order streamed, the reverse version cannot emit the first element until the whole tree is walked, because reversal needs the full list. In that case the one-stack version is preferable despite the extra state.
Mutating the tree during traversal breaks both versions in the same way. If a callback reassigns node.left after the node is pushed, the walk follows the new structure and can revisit or skip subtrees. A cycle introduced by a bad update also causes an infinite loop, since neither version tracks visited nodes. That is outside the binary tree contract, but naming it shows the assumption: finite, acyclic, and unmodified during the walk. A null root is handled explicitly, and a single node returns [root.val] with no special case beyond the empty check.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Merge overlapping intervals, and how would you extend it to streaming intervals arriving out of order?
Reported in Leonardo Graduate Software Engineer Interview Questions & Prep Guide 2026 | InterviewSense
The 90-second answer
For the static version, sort by start and sweep once, keeping the current merged interval. If the next interval starts after the current end, emit the current one and start a new one. Otherwise extend the current end to the maximum of the two ends. That is O(n log n) for the sort and O(n) for the sweep, O(n) output space.
For streaming intervals arriving out of order, I keep the merged set sorted and disjoint at all times. Each insertion finds the intervals that overlap or touch the new one, merges them into one, and reinserts it. With a balanced tree keyed by start, that is O(log n + k) per insertion, where k is the number of intervals absorbed. The catch is emission: I cannot safely emit a merged interval until a watermark passes its end, because a late interval could still bridge it to the next one.
Static merge
# Python 3.12
def merge(intervals: list[list[int]]) -> list[list[int]]:
if not intervals:
return []
intervals.sort(key=lambda iv: iv[0])
merged = [intervals[0][:]]
for start, end in intervals[1:]:
last = merged[-1]
if start <= last[1]: # overlaps or touches; use < if touching stays separate
last[1] = max(last[1], end)
else:
merged.append([start, end])
return mergedWorked trace for [[1,3],[2,6],[8,10],[15,18],[9,12]]:
| Step | Interval | Action | Merged so far |
|---|---|---|---|
| 1 | [1,3] | start current | [[1,3]] |
| 2 | [2,6] | 2 <= 3, extend end to 6 | [[1,6]] |
| 3 | [8,10] | 8 > 6, emit [1,6] | [[1,6],[8,10]] |
| 4 | [9,12] | 9 <= 10, extend end to 12 | [[1,6],[8,12]] |
| 5 | [15,18] | 15 > 12, emit [8,12] | [[1,6],[8,12],[15,18]] |
Sorting dominates. If intervals arrive nearly sorted, insertion sort drops the sweep to O(n log n) worst case but O(n) in practice, which is worth mentioning only if the interviewer asks about input shape.
Streaming, out of order
Maintain disjoint intervals in a balanced search tree keyed by start, for example bisect over a sorted list for a small in-memory set, or sortedcontainers / a B-tree in production. Insertion logic:
Trace, inserting in arrival order:
| Arrival | State after insert | Note |
|---|---|---|
| [8,10] | [[8,10]] | first interval |
| [1,3] | [[1,3],[8,10]] | disjoint, inserted before |
| [2,6] | [[1,6],[8,10]] | absorbs [1,3] |
| [15,18] | [[1,6],[8,10],[15,18]] | disjoint |
| [9,16] | [[1,6],[9,18]] | bridges [8,10] and [15,18], absorbs both |
The last row is the failure mode people miss. If I had emitted [8,10] as final when it arrived, [9,16] would invalidate that output. So emission needs a watermark: only release intervals whose end is below the watermark, meaning no future interval with start at or below that end is expected. Without a lateness bound, the honest answer is that final output is impossible and I emit provisional merges that a downstream consumer must retract or supersede.
| Approach | Insert cost | Memory | When it fits |
|---|---|---|---|
Sorted list + bisect | O(n) shift per insert | O(n) | Up to roughly 10^4 live intervals, simple to debug |
| Balanced tree keyed by start | O(log n + k) | O(n) | Production streaming, large live set |
| Re-sort and re-merge in batches | O(m log m) per batch of m | O(m) | Low rate, or when simplicity beats latency |
Failure modes and follow-ups
Duplicate and touching intervals: decide the contract up front. With start <= last_end, [1,3] and [3,5] merge into [1,5]. With start < last_end, they stay separate. For coverage problems the first is usually right, for scheduling with back-to-back slots the second can be. State the choice, do not let it be implicit.
Unbounded lateness: a single very late interval can merge two large components and force a retraction cascade. Cap it with a watermark and a late-data policy, drop or side-output intervals arriving past the bound, and count them so the drop is visible in metrics.
Memory growth: if intervals never merge, the live set grows without bound. That is a property of the input, not a bug, but I would alert on live interval count and oldest unemitted end so a stuck watermark pages before memory does.
If the interviewer pushes on scale, the next step is partitioning by key, merging per partition, and only combining across partitions at emission time. The per-partition invariant stays the same: sorted, disjoint, watermark-gated output.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Design a rate limiter for a public API?
Reported in Leonardo Graduate Software Engineer Interview Questions & Prep Guide 2026 | InterviewSense
The 90-second answer
I would ask three things first: who is being limited, what unit is counted, and what happens when the limit is hit. For a public API I will assume the caller is identified by an API key, with IP as a fallback for anonymous traffic, the unit is requests per key per minute, and excess traffic gets a 429 with a Retry-After header. Those assumptions change the design more than the algorithm does.
My default is a token bucket stored in Redis and checked atomically before the request reaches the service. Each key gets a bucket with a capacity for burst and a refill rate for the sustained limit. A request consumes one token if one is available. That gives a client a short burst for legitimate spikes while keeping the long-term rate bounded, which is what protects downstream databases and third-party quotas.
Why token bucket, and when I would pick something else
| Algorithm | Behaviour | Main cost | When I would use it |
|---|---|---|---|
| Fixed window counter | Counts in the current minute, resets at the boundary | A client can send 2x the limit across two adjacent windows | Simple internal APIs with loose limits |
| Sliding window log | Stores every timestamp and counts the last minute | Memory grows with request rate, one entry per request | Low-rate admin endpoints where precision matters |
| Sliding window counter | Weights the previous window by elapsed time | Approximation, usually within a few percent | High-rate public APIs where a log is too large |
| Token bucket | Refills continuously, allows a defined burst | Needs atomic updates in a distributed store | Public APIs with burst tolerance, which is the common case |
Fixed window has a concrete failure mode worth naming in the interview. With a limit of 600 per minute, a client can send 600 requests at 12:00:59 and another 600 at 12:01:01. The service sees 1,200 requests in three seconds while every individual window looks compliant. Token bucket avoids that because the refill is continuous.
Worked trace
Assume capacity 100, refill 10 tokens per second, which is 600 per minute sustained. The bucket starts full.
| Time | Tokens before | Request | Tokens after | Result |
|---|---|---|---|---|
| 0.0 s | 100 | 1 | 99 | allowed |
| 0.0 s | 99 | 50 more in the same burst | 49 | allowed |
| 1.0 s | 59 after refill | 1 | 58 | allowed |
| 5.0 s | 98 after refill | 1 | 97 | allowed |
| 5.0 s | 97 | 120 rapid requests | 0, then 429 for the rest | 97 allowed, 23 rejected |
The last row is the point. The client gets its burst, then a 429 with Retry-After: 1 and X-RateLimit-Remaining: 0. A well-behaved client backs off for a second and resumes. A client that ignores the header keeps getting rejected without consuming service capacity beyond the Redis check.
Distributed implementation
The check and the decrement have to be one atomic step, or two concurrent requests can both read one remaining token and both pass. In Redis I would use a Lua script so the read, refill calculation and write happen together:
-- KEYS[1] = bucket key, ARGV[1] = capacity, ARGV[2] = refill per second
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local now = tonumber(ARGV[3])
local tokens = tonumber(b[1]) or tonumber(ARGV[1])
local ts = tonumber(b[2]) or now
tokens = math.min(tonumber(ARGV[1]), tokens + (now - ts) * tonumber(ARGV[2]))
if tokens >= 1 then
tokens = tokens - 1
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], 120000)
return {1, math.floor(tokens)}
end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)
return {0, 0}I would pass server time in rather than trusting the client clock, and set a TTL slightly above the refill period so idle keys disappear. That TTL matters for cardinality: a public API can create millions of distinct keys from spoofed or trial credentials, and buckets without expiry will fill Redis.
Failure modes I would raise unprompted
Redis unavailable is the first one. If the limiter fails closed, a Redis outage becomes a full API outage. If it fails open, abuse traffic flows through during the outage. For a public API I would fail open for authenticated keys with a local in-process bucket as a backstop, and fail closed for anonymous traffic, because anonymous abuse is the larger risk. The local bucket is approximate across instances, but it bounds the damage while Redis is down.
Clock skew is the second. Refill math depends on timestamps, so instances with drifting clocks will refill at different rates. Using Redis server time inside the script, or a single time source per region, keeps that consistent.
Shared IPs are the third. Limiting only by IP punishes everyone behind a corporate NAT or a mobile carrier gateway. That is why the API key is the primary identity and IP is only the fallback, with a much lower limit for anonymous callers.
Finally, I would put the limiter at the gateway, not inside each service. A service-level check can still exist for expensive endpoints, such as a search or export route with a limit of 10 per minute per key, but the global per-key limit belongs at the edge so rejected traffic never reaches the application tier.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Design a notification service that fans out to millions of devices?
Reported in Leonardo Graduate Software Engineer Interview Questions & Prep Guide 2026 | InterviewSense
The 90-second answer
I would clarify four things first: what triggers a notification, who receives it, which channels count, and how late is too late. Assume an internal event such as an alert or a message for a user, an audience of up to 10 million registered devices, delivery over APNs or FCM for mobile, WebSocket for connected clients, and email or SMS as fallback. Offline devices get store and forward with a time to live, because a push provider will not hold a message for a device that stays offline for a week.
The core split is ingestion from fan-out. Producers publish one event. A fan-out service resolves the audience, writes per-device delivery tasks to a durable queue, and workers send in batches through the provider. That separation lets a burst of 1 million recipients be absorbed without blocking the producer, and lets workers retry one device without resending to everyone.
Sizing the fan-out
Worked example, figures labelled as assumptions: 10 million registered devices, one broadcast reaches 20 percent, so 2 million deliveries. If the deadline is 60 seconds, the service must sustain 2,000,000 / 60 = about 33,000 deliveries per second. With a batch of 500 per provider call, that is about 66 calls per second per channel, before retries. If a worker handles 2,000 deliveries per second, you need at least 17 workers active, and I would provision for 40 to leave headroom for a provider slowdown and a worker loss. The queue, not the provider, is the shock absorber. Partition it by channel and by hash of device id so one bad provider does not stall the others.
| Channel | Use it when | Limit to design around |
|---|---|---|
| APNs / FCM push | Mobile app installed, device may be offline | Invalid or expired tokens, provider rate limits, payload about 4 KB |
| WebSocket | Client is connected now, low latency matters | Connection churn, need for reconnect and replay |
| Email / SMS | No app, or push failed and message is important | Cost per message, slower, strict consent and opt-out rules |
Delivery task and idempotency
Each task carries the event id, device id, channel, payload version, and a send deadline. The worker checks preferences and suppression before sending, then records the provider message id. Retries reuse the same idempotency key so a timeout does not create a duplicate push.
# Python 3.12, one worker loop
def deliver(task):
if not prefs.allows(task.user_id, task.category):
return mark(task, "suppressed")
if receipts.seen(task.idempotency_key):
return mark(task, "duplicate")
try:
msg_id = provider.send_batch(task.device_token, task.payload)
receipts.record(task.idempotency_key, msg_id)
return mark(task, "sent")
except InvalidToken:
tokens.deactivate(task.device_token)
return mark(task, "invalid_token")
except ProviderThrottled as e:
queue.retry_later(task, delay=e.retry_after)
return mark(task, "throttled")Failure modes I would name in the interview
Invalid tokens accumulate fast. If 5 percent of tokens are dead and you never prune them, every broadcast wastes 5 percent of its sends and risks provider reputation. Receipts and token feedback loops feed a cleanup job.
Provider throttling is the second one. APNs and FCM both throttle by app and by rate. The worker must honour retry-after, spread sends with jitter, and shed low priority traffic first. Priority matters here: a safety alert should preempt a marketing digest, so the queue needs at least two priority lanes.
Duplicates are the third. At-least-once delivery from the queue plus a provider timeout will resend some messages. The client should dedupe on event id, and the payload should carry that id. Exactly-once end to end is not a credible claim across a third party provider.
Finally, audience resolution can be the bottleneck. Resolving 2 million recipients from group membership at send time can take longer than the send itself. I would materialise large audiences into a snapshot table when the event is accepted, then fan out from the snapshot. That also makes the send auditable: you can answer exactly who was targeted, which matters for regulated or safety related notifications.
I would close by stating what I would not build: a direct database write per device in the request path, a single queue for all channels, and no receipt tracking. Those three choices turn a burst into an outage and make every retry a duplicate.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Given a large dataset of flight paths, write a function to efficiently detect potential mid-air collisions within a specified proximity threshold and time window when the dataset is too large to fit into memory?
Reported in Leonardo Software Engineer interview questions and what they test
The 90-second answer
I would not load the tracks. I would sort them externally by time, sweep a sliding time window, and index only the flights active in that window in a spatial grid whose cell size equals the proximity threshold. Two flights can only collide if they are in the same or neighbouring cells at overlapping times, so I never compare every pair.
Assume each record is (flight_id, t, lat, lon, alt_m) sampled every few seconds, the threshold is lateral distance D (for example 5 NM, about 9,260 m) and vertical separation V (for example 300 m), and positions between samples are interpolated linearly. That last assumption matters. Checking only sampled points misses a crossing that happens between two samples 30 seconds apart. For a candidate pair I compute the closest approach of the two interpolated segments in 3D, not just point to point distance.
# Python 3.11, streaming sweep. Input is an iterator sorted by t
# (produced by an external sort, e.g. sort -k2 -n or a spill-to-disk sort).
import math
from collections import defaultdict
R_EARTH = 6_371_000.0
def to_local_m(lat, lon, lat0, lon0):
x = math.radians(lon - lon0) * R_EARTH * math.cos(math.radians(lat0))
y = math.radians(lat - lat0) * R_EARTH
return x, y
def detect_collisions(points, D_m, V_m, window_s):
active = {} # flight_id -> last point
grid = defaultdict(list)
cell = D_m # cell size = threshold, so neighbours suffice
seen = set() # (min_id, max_id) already reported
for p in points:
# expire flights whose last point is older than the window
for fid in [f for f, q in active.items() if p.t - q.t > window_s]:
del active[fid]
x, y = to_local_m(p.lat, p.lon, p.lat0, p.lon0)
cx, cy = int(x // cell), int(y // cell)
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for fid in grid.get((cx + dx, cy + dy), []):
if fid == p.flight_id or fid not in active:
continue
q = active[fid]
if abs(p.alt_m - q.alt_m) > V_m:
continue
pair = (min(fid, p.flight_id), max(fid, p.flight_id))
if pair in seen:
continue
if closest_approach(q, p) < D_m: # segment-segment, see below
seen.add(pair)
yield pair, p.t
active[p.flight_id] = p
grid[(cx, cy)].append(p.flight_id)closest_approach projects both segments into a local east-north-up frame around the pair, then solves for the parameter values s, u in [0,1] minimising |A + s*(B-A) - (C + u*(D-C))|. That is a small quadratic, closed form, and it catches the between-samples case. If the minimum is under D_m and the vertical gap at that instant is under V_m, it is a potential conflict. I would report the time of closest approach, not the sample time.
Why this scales. The grid turns an O(N^2) all-pairs check into work proportional to the number of flights actually near each other. With N = 10^7 points and, say, 200 flights active in a 60 second window, the active set is tiny compared with the dataset. Memory is O(active flights), not O(N). If even one time bucket is too dense to hold, I partition the sorted stream by (time_bucket, cell_x, cell_y) to disk and process one partition at a time, replicating a one-cell halo and a one-window overlap so pairs on a boundary are not lost. Duplicates from the halo are removed with the seen set keyed on the sorted flight id pair.
Worked trace, D = 9,260 m, window 60 s, hypothetical figures:
| t (s) | Event | Active flights | Grid check | Result |
|---|---|---|---|---|
| 0 | A enters cell (0,0) | 1 | none | none |
| 20 | B enters cell (1,0) | 2 | A in neighbour cell | closest approach 4,100 m, emit (A,B) |
| 45 | C enters cell (0,0), alt differs by 900 m | 3 | A, B checked, vertical filter rejects | none |
| 90 | A expires, last point 70 s old | 2 | none | none |
Failure modes I would name. First, sampling gaps. If a feed drops points for 120 seconds, linear interpolation invents a path. I would cap interpolation to a maximum gap, for example 60 s, and flag longer gaps as unknown rather than clear. Second, GPS and timestamp error. A 50 m horizontal error is noise against a 9 km threshold, but clock skew between feeds can shift the window. I would require a common time source and treat records with no timestamp as unusable, not as zero. Third, the grid degrades in dense terminal airspace where hundreds of flights share a cell. The neighbour check then approaches all-pairs within that cell. The fix is a finer cell with a wider neighbour search, or a KD-tree per cell, chosen after measuring cell occupancy. Fourth, 2D-only checks. Two aircraft can be laterally close and vertically separated by 3,000 ft, which is not a conflict under most separation standards. The vertical filter must be applied at the time of closest approach, not at sample times.
I would validate against a brute-force all-pairs run on a sampled subset that fits in memory, and check that the streaming version finds the same pairs. That test catches halo and expiry bugs, which are the ones that silently drop pairs at partition boundaries.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Implement an algorithm to schedule critical tasks with dependencies and deadlines, or determine if no valid schedule exists?
Reported in Leonardo Software Engineer interview questions and what they test
The 90-second answer
I would state the model first. One processor, non-preemptive tasks, each task i has processing time p[i] and deadline d[i], and precedence edges u -> v meaning u finishes before v starts. A schedule is an ordering of all tasks such that every task finishes by its deadline and every edge goes forward. I would use Lawler's backward algorithm, which is exact for this model with arbitrary processing times, not only unit tasks.
Work backwards from the end. Maintain the set of unscheduled tasks and t, the total processing time of that set, which is the completion time of the last unscheduled task. A task is eligible when all of its successors are already scheduled, so it can go last among the unscheduled tasks. Pick the eligible task with the largest deadline and schedule it last, ending at t. If t > d[i], no feasible schedule exists. Otherwise remove it, subtract p[i] from t, and repeat. If tasks remain but none is eligible, the precedence graph has a cycle and no schedule exists.
# Python 3.11, 1 | prec | feasibility, Lawler's algorithm
import heapq
def schedule(tasks):
# tasks: {id: (processing_time, deadline, [predecessors])}
succ = {i: [] for i in tasks}
for i, (_, _, preds) in tasks.items():
for p in preds:
succ[p].append(i)
unscheduled_succ = {i: len(succ[i]) for i in tasks}
# max-heap by deadline via negated key
ready = [(-tasks[i][1], i) for i in tasks if unscheduled_succ[i] == 0]
heapq.heapify(ready)
t = sum(p for p, _, _ in tasks.values())
order = [] # built backwards, last task first
while ready:
neg_d, job = heapq.heappop(ready)
if t > -neg_d:
return None # this task would finish after its deadline
order.append(job)
t -= tasks[job][0]
for pred in tasks[job][2]:
unscheduled_succ[pred] -= 1
if unscheduled_succ[pred] == 0:
heapq.heappush(ready, (-tasks[pred][1], pred))
if len(order) != len(tasks):
return None # cycle: remaining tasks never became eligible
return list(reversed(order))
schedule({'S': (1, 1, []), 'A': (1, 3, ['S']), 'B': (1, 3, ['S']), 'C': (1, 4, ['A', 'B'])})
# ['S', 'B', 'A', 'C']Worked trace
S is a sensor reading, A and B are control adjustments that need it, C is telemetry that needs both. All processing times are 1.
| Backward step | t before pick | Eligible (no unscheduled successors) | Picked (largest deadline) | Check |
|---|---|---|---|---|
| 1 | 4 | C | C, d=4 | 4 <= 4, ok |
| 2 | 3 | A, B | A, d=3 | 3 <= 3, ok |
| 3 | 2 | B | B, d=3 | 2 <= 3, ok |
| 4 | 1 | S | S, d=1 | 1 <= 1, ok |
Reversed, the schedule is S, B, A, C, finishing at 1, 2, 3, 4. Running time is O((n + m) log n) for n tasks and m edges, memory O(n + m).
Two cases show why the backward rule and the t check matter. Tasks with deadlines 100 and 1, both length 1, are feasible: t starts at 2, the deadline-100 task is picked first and ends at 2, then the deadline-1 task ends at 1. Starting the backward pass at the maximum deadline, 100, and rejecting when a deadline is below the current slot would falsely reject this instance. Conversely, three length-1 tasks with deadlines 1, 1, 1 are infeasible: t starts at 3, the largest deadline is 1, and 3 > 1 rejects immediately. No task is ever placed at slot 0.
Why backwards, and where it stops being exact
Forward earliest-deadline-first on the ready set is a heuristic once precedence exists. It can run a task early that blocks a successor with a tight deadline, then report infeasibility for a feasible instance. Scheduling backwards fixes successors first, so a predecessor can never be pushed past one. This is Lawler's algorithm for 1 | prec | f_max, and deadline feasibility is the special case where f_max is the maximum lateness.
The model, not the processing times, is what makes the problem hard. Adding release dates makes 1 | r_j, prec | f_max NP-hard, as does moving to multiple processors or adding a shared resource such as a bus that tasks also need. For those cases I would switch to a CP-SAT model with one interval per task, NoOverlap per processor or resource, precedence constraints, and deadline constraints, and let the solver prove infeasibility. For preemptive tasks on one processor, EDF with a check at each deadline is exact.
In a flight or robotics loop, a bare None is not enough operationally. I would return which check failed: the task whose deadline was exceeded at t, or the set of tasks left in a cycle, plus the partial order built so far. That tells the caller whether to drop a low-priority task, relax a deadline, or fix the dependency graph.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Design a distributed system for real-time monitoring of Leonardo's drone fleet?
Reported in Leonardo Software Engineer interview questions and what they test
The 90-second answer
I would treat this as three separate problems: getting telemetry off aircraft that lose connectivity, keeping a current picture of every drone in one place, and alerting on the few events that need a human in seconds. I will assume a fleet of 10,000 drones, each sending position, altitude, speed, heading, battery and link quality at 1 Hz in normal flight and 4 Hz during takeoff, landing and alerts. That is the design point I will size for, and I can scale the numbers up or down.
Drones publish over MQTT or HTTPS to a ground station gateway, which buffers to disk when the backhaul drops and forwards with the original timestamps. The ingest API authenticates each drone with a per-device certificate, validates the schema, and writes to Kafka keyed by drone ID. A stream processor maintains the latest state per drone, detects stale or impossible telemetry, and writes hot state to Redis and history to a time series store such as TimescaleDB or InfluxDB. The operator console reads hot state for the map and queries history for replay.
Sizing and storage
At 10,000 drones and 1 Hz, with roughly 500 bytes per message after framing, ingest is 5 MB/s, about 40 Mbps, and 432 GB per day raw. That fits comfortably on a small Kafka cluster with 7 day retention, about 3 TB before replication. Hot state is tiny: 10,000 keys in Redis. History is the cost. Downsampling to 10 second aggregates after 24 hours cuts storage by roughly 90 percent while keeping enough resolution for incident review. I would keep raw data for 7 days, 10 second aggregates for 90 days, and 1 minute aggregates for 2 years.
| Signal | Check in stream processor | Action |
|---|---|---|
| Heartbeat age | No message for more than 15 seconds | Mark drone stale on map, page if airborne |
| Position jump | Implied speed above 300 m/s between samples | Flag sensor fault, exclude from geofence alert |
| Battery | Below 20 percent, or drain rate above 2 percent per minute | Alert operator, suggest return to base |
| Geofence | Position outside authorised polygon for more than 5 seconds | Immediate alert, freeze last known track |
| Link quality | Packet loss above 30 percent over 30 seconds | Degrade display confidence, raise telemetry rate |
Handling the messy parts
Clock skew and out of order delivery are normal. Every message carries device_ts, seq and drone_id. The processor drops duplicates by (drone_id, seq), accepts late data up to 60 seconds for history, but never lets late data overwrite current state. Current state only moves forward on device_ts.
# Stream processor, Python 3.12, checked against Kafka consumer semantics
def apply(msg, state):
key = (msg["drone_id"], msg["seq"])
if key in state.seen:
return # duplicate delivery from gateway retry
state.seen.add(key)
cur = state.latest.get(msg["drone_id"])
if cur and msg["device_ts"] < cur["device_ts"]:
state.history.append(msg) # late, keep for replay only
return
state.latest[msg["drone_id"]] = msg
if msg["battery"] < 20:
state.alert(msg["drone_id"], "low_battery")Backpressure matters more than raw throughput. If Kafka lag passes 30 seconds, I would shed the 4 Hz burst stream first, keep 1 Hz heartbeats, and show operators a clear degraded mode banner. A map that silently shows 2 minute old positions as live is worse than one that says data is stale.
Failure modes I would name in the interview
A ground station partition can make a whole region look dead. The gateway buffer and the stale marker handle that, but the console must distinguish "drone silent" from "gateway silent" by tracking gateway heartbeats separately. A bad firmware release can flood ingest with malformed messages, so the ingest API enforces a strict schema and a per-device rate limit of 10 messages per second, with excess rejected and counted. A time series store outage should not block ingest, so Kafka remains the buffer and the processor replays from the last committed offset.
For Leonardo specifically, I would assume sovereign or on premise deployment is likely, so no dependency on a public cloud region for the control path. Telemetry and video stay on separate networks, video never goes through the telemetry pipeline, and all drone identities are provisioned through the fleet PKI rather than shared API keys. Monitoring is read only by design. If the interviewer asks about control commands, I would split that into a separate, audited command service with its own authentication and safety interlocks, and keep it out of the monitoring path so a monitoring outage cannot affect flight safety.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Design the high-level architecture for a new secure communication module for Leonardo's aircraft, considering encryption, key management, data integrity, and integration with existing aircraft systems?
Reported in Leonardo Software Engineer interview questions and what they test
The 90-second answer
I would not put this on the flight-critical bus. I would build it as a partitioned gateway module in the Integrated Modular Avionics (IMA) cabinet, certified to DO-178C at a lower Design Assurance Level than flight control, that terminates external and maintenance traffic and forwards only validated, integrity-checked messages onto the certified internal network. That separation is the first decision. It limits the blast radius if the crypto code has a bug, and it keeps the safety case for the flight control partition unchanged.
Assumptions I would state up front: the module handles mission data, telemetry, maintenance downloads and ground link traffic, not primary flight control. The internal network is ARINC 664 / AFDX or switched Ethernet with ARINC 653 partitioning. The ground side has a PKI. If any of those are wrong, the design changes, and I would ask which traffic classes are in scope before going further.
Encryption and integrity, as one mechanism
Use AEAD, not encrypt-then-MAC built by hand. AES-256-GCM for bulk data, with a 96-bit nonce constructed as a 64-bit sequence number plus 32-bit partition ID, never reused under the same key. Each frame carries a 16-byte tag. For a 1,400-byte AFDX frame that is 28 bytes of overhead, about 2 percent, and hardware AES on a modern IMA processor adds well under 0.5 ms per frame, which I would verify against the virtual link latency budget rather than assert.
// Checked against C11 with an AES-GCM library backed by the HSM.
// Nonce is never random: seq is monotonic per session key.
int seal_frame(session_key_t *k, uint64_t seq, const uint8_t *pt, size_t len,
uint8_t *out, size_t *out_len) {
uint8_t nonce[12] = {0};
memcpy(nonce, &seq, 8); // seq in first 8 bytes
nonce[8] = k->partition_id; // binds frame to sender partition
return aes_gcm_encrypt(k->key, nonce, pt, len, out, out_len);
}Replay protection comes from that sequence number. The receiver keeps a sliding window of the last 1,024 sequence numbers, rejects anything older or already seen, and raises a counter in the health log. A timestamp alone is not enough, because aircraft clocks can jump when GPS is lost.
Key management
Keys never live in application memory. A discrete HSM or TPM on the module holds a per-aircraft device key pair, generated at manufacture and never exported. The ground PKI issues a device certificate for that key. Session keys are ephemeral: ECDH on P-256 between the module and the ground station, authenticated by those device certificates, then run through HKDF to derive separate encryption and signing keys. Session keys rotate every 15 minutes or 10,000 frames, whichever comes first, and are zeroised on partition reset.
Revocation is the hard part on an aircraft that may be offline for days. I would not depend on live OCSP. The module carries a signed, dated revocation list updated at every maintenance visit, and it refuses new ground sessions if that list is more than 30 days old. That is a deliberate trade-off: it can ground a legitimate session after a long deployment, but it fails closed on a compromised certificate. I would surface that policy to operations before design freeze, because it is a business decision disguised as a crypto one.
Integration with existing systems
The module speaks three interfaces and nothing else. Inbound, a hardened parser for the external protocol, with a strict schema and a maximum frame size enforced before any allocation. In the middle, a gateway that maps validated fields onto AFDX virtual links, with per-link rate limits so a flood on the ground link cannot starve avionics traffic. Outbound, a health and audit interface that reports session failures, replay rejections and key age to the central maintenance system. The module runs in its own ARINC 653 partition with no shared memory with flight-critical partitions, and its configuration is signed and checked at boot under DO-355. A fault in this partition must not be able to write to another partition, which the IMA kernel enforces, not the application.
| Failure mode | Detection | Response |
|---|---|---|
| Nonce reuse after reset | Sequence number goes backwards under same session key | Abort session, zeroise keys, log event |
| Ground certificate revoked | Revocation list check at session setup | Refuse session, report to maintenance |
| Malformed external frame | Parser rejects before allocation, frame counter increments | Drop frame, rate-limit source, no partition restart |
| HSM failure | Boot self-test and periodic health check fail | Module stays offline, avionics continue on internal bus |
| Clock skew breaks freshness check | Sequence window still passes, timestamp drift alarm | Rely on sequence numbers, flag time source fault |
What I would not do
I would not roll my own cipher, put long-term keys in a config file, or terminate TLS in a general-purpose web stack inside the IMA cabinet. Each of those has failed in production elsewhere. I would also not claim this design is secure without the DO-326A security risk assessment and penetration testing against the actual parser, because the parser, not AES, is where these systems usually break.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Implement a function that returns an optimized path for an autonomous drone considering fuel constraints and avoiding known hazards?
Reported in Leonardo Software Engineer interview questions and what they test
The 90-second answer
I would model the airspace as a weighted grid graph and run A* from start to goal. Each cell has a traversal cost in fuel, hazard cells are either blocked or heavily penalised, and any partial path whose cumulative fuel exceeds usable capacity is pruned. If the goal is unreachable within fuel, the function returns no path rather than a path the drone cannot fly. That distinction matters for a Leonardo platform, where returning an infeasible plan is worse than admitting none exists.
Assumptions I would state first: a static grid for this interview version, 8-connected movement, fuel consumption proportional to distance flown, a fixed reserve that is never planned against, and known hazards supplied as blocked or high-cost cells. Wind, altitude and dynamic hazards change the cost function, not the search.
import heapq
def find_path(grid, start, goal, fuel_capacity, reserve, fuel_per_step=1.0):
# grid[r][c]: 0 = free, 1 = hazard (blocked), 2 = hazard zone (costly)
rows, cols = len(grid), len(grid[0])
usable = fuel_capacity - reserve
if grid[start[0]][start[1]] == 1 or grid[goal[0]][goal[1]] == 1:
return None
# (f, g, cell, parent)
open_heap = [(0.0, 0.0, start, None)]
came_from = {start: None}
best_g = {start: 0.0}
dirs = [(-1,0,1.0),(1,0,1.0),(0,-1,1.0),(0,1,1.0),
(-1,-1,1.414),( -1,1,1.414),(1,-1,1.414),(1,1,1.414)]
while open_heap:
_, g, cell, _ = heapq.heappop(open_heap)
if g > best_g.get(cell, float('inf')):
continue
if cell == goal:
path, cur = [], cell
while cur is not None:
path.append(cur); cur = came_from[cur]
return list(reversed(path))
r, c = cell
for dr, dc, dist in dirs:
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
if grid[nr][nc] == 1:
continue
# Prevent cutting the corner past a blocked orthogonal neighbour
if dr and dc and (grid[r+dr][c] == 1 or grid[r][c+dc] == 1):
continue
step_cost = dist * fuel_per_step
if grid[nr][nc] == 2:
step_cost *= 5 # hazard zone: flyable, but expensive in risk/fuel
ng = g + step_cost
if ng > usable:
continue # cannot reach this cell and still keep the reserve
if ng < best_g.get((nr, nc), float('inf')):
best_g[(nr, nc)] = ng
came_from[(nr, nc)] = cell
h = ((nr - goal[0])**2 + (nc - goal[1])**2) ** 0.5 * fuel_per_step
heapq.heappush(open_heap, (ng + h, ng, (nr, nc), cell))
return NoneThe heuristic is Euclidean distance times fuel per step. It never overestimates the true fuel cost on free cells, so A* stays optimal on this graph. Hazard-zone cells break that neatness if I add a penalty that the heuristic ignores, which is fine: the heuristic still underestimates, so optimality holds, but the search explores more of the hazard zone than it would with a perfect heuristic.
Worked trace
Grid 3x3, start (0,0), goal (2,2), fuel capacity 10, reserve 2, so usable fuel is 8. Cell (1,1) is blocked.
| Step | Cell popped | g (fuel used) | h | f = g + h | Decision |
|---|---|---|---|---|---|
| 1 | (0,0) | 0.00 | 2.83 | 2.83 | Expand to (0,1), (1,0) |
| 2 | (0,1) | 1.00 | 2.24 | 3.24 | Expand to (0,2), (1,2) via diagonal blocked, so via (0,2) |
| 3 | (1,0) | 1.00 | 2.24 | 3.24 | Expand to (2,0), (2,1) |
| 4 | (0,2) | 2.00 | 2.00 | 4.00 | Expand to (1,2) |
| 5 | (2,0) | 2.00 | 2.00 | 4.00 | Expand to (2,1) |
| 6 | (1,2) | 3.00 | 1.00 | 4.00 | Expand to (2,2) |
| 7 | (2,2) | 4.00 | 0.00 | 4.00 | Goal, total fuel 4.00, within usable 8 |
Returned path: (0,0), (0,1), (0,2), (1,2), (2,2). The direct diagonal through (1,1) is rejected twice, once because the cell is blocked and once by the corner-cutting check.
Why A here, and when I would not use it*
| Approach | Strength | Weakness for this problem |
|---|---|---|
| Dijkstra | Optimal, simple | Explores in all directions, slower on large grids |
| A* | Optimal with admissible heuristic, goal-directed | Needs a heuristic that never overestimates |
| RRT* / sampling planners | Handle continuous space and high dimensions | Probabilistic, harder to certify, path quality varies per run |
| BFS | Fine for unweighted grids | Ignores fuel and hazard costs entirely |
For a grid up to a few hundred cells per side, A* is the right default. For a point cloud or continuous 3D volume, I would switch to a sampling planner or a voxel grid with the same cost model, and I would say so rather than force A* onto continuous space.
Failure modes I would name in the interview
No path within fuel: the function returns None. The caller then has to decide, for example, whether to route via a refuel or loiter point. Silently returning the shortest path regardless of fuel hides that decision.
Reserve erosion: if wind or payload raises consumption above fuel_per_step, the planned path can breach the reserve in flight. In production I would replan on a timer and on deviation from the corridor, and I would treat the reserve as a hard constraint in the search, as above, not as a warning after it.
Stale hazards: the grid is a snapshot. A hazard reported after planning invalidates the path. The mitigation is replanning with updated cells, plus inflating hazard cells by the drone's turning radius and localisation error so the planned path keeps clearance.
Grid artefacts: 8-connected paths look jagged and can clip hazard corners. The corner-cutting check above is a small fix. A production system would smooth the path afterwards and re-check clearance against the inflated hazards before committing it.
Complexity is O(V log V) in the number of cells visited, with O(V) memory for best_g and came_from. On a 1000 by 1000 grid that is up to a million cells, which is acceptable offline and borderline for a tight onboard replanning budget, so I would mention a hierarchical grid or a bounded search window as the next step if latency mattered.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12What interests you specifically about working in the aerospace industry and at Leonardo, given your software engineering background?
Reported in Leonardo Software Engineer interview questions and what they test
The 90-second answer
I want to work where software is physically coupled to hardware for decades, and Leonardo is one of the few places in Europe where that coupling spans helicopters, fast jets, trainers and space systems under one engineering culture. My background is in backend and distributed systems, where I care about correctness under failure, latency budgets and long lived data. Aerospace takes those same concerns and makes them non negotiable. A race condition in a consumer service costs a retry. The same race in a flight control partition can cost an aircraft.
What draws me specifically is the constraint set. On a Leonardo AW169 or AW101, mission and flight critical functions run on Integrated Modular Avionics with ARINC 653 time and space partitioning. You cannot just scale out or deploy on Friday. Software is developed to DO-178C, hardware to DO-254, system behaviour to ARP4754A, and every requirement has to trace to a test that proves it. That discipline is what I want to learn properly, not as process theatre but as engineering. I have written code where we argued about p99 latency. I want to work where a 10 ms jitter budget is derived from control theory and verified on a rig before it ever flies.
Leonardo also gives breadth I would not get at a pure software firm. The same engineer can touch the M-346 training platform, Eurofighter Typhoon mission systems, ATR avionics, and the electronics business in Luton and Edinburgh that builds secure communications and sensors. That matters because the interesting software problems sit at the seams: sensor fusion, deterministic networking, cyber security for a platform that will be in service until the 2050s, and autonomy that has to be certifiable rather than just accurate in simulation.
Why the constraints are the attraction
| Dimension | Typical product software | Leonardo flight software |
|---|---|---|
| Change cycle | Daily deploys, feature flags | Certification baseline, formal change control |
| Failure cost | Rollback, apology, churn | Hazard analysis, safety case, fleet grounding |
| Lifetime | 2 to 5 years | 25 to 40 years, spares and toolchains preserved |
| Verification | Unit tests, load tests, canary | Requirements trace, MC/DC coverage at Level A, HIL testing |
| Determinism | Best effort latency | Partitioned scheduling, worst case execution time analysis |
That last row is the concrete difference. A partition schedule is not a vague preference for speed. It is a table that has to be proven.
// ARINC 653 style partition window, simplified
// Each partition gets a fixed window in a 100 ms major frame.
// A partition that overruns its window is contained, not allowed
// to starve flight control.
typedef struct { unsigned int window_ms; unsigned int offset_ms; } Window;
static const Window schedule[] = {
{ 20, 0 }, // flight control, Level A
{ 30, 20 }, // mission systems
{ 10, 50 }, // health monitoring
{ 40, 60 }, // payload and logging
};Working on that kind of code means thinking about worst case, not average case. My distributed systems experience transfers directly: idempotency, backpressure, health monitoring and fault isolation are the same ideas, just with a safety case attached and no option to restart the machine mid flight.
The arithmetic that changes how you code
Suppose a defect escapes into a fleet of 500 helicopters and requires a software update campaign. Even at a hypothetical 40 engineer hours per aircraft for reflashing, regression testing and documentation, that is 20,000 hours before you count downtime. In product software that calculation pushes you toward shipping fast and fixing forward. In aerospace it pushes you toward model based design, static analysis, and proving the partition cannot overrun. I find that trade off more interesting because the cost model is honest. You feel the consequence of a sloppy interface in the design review, not in a postmortem.
What I would bring and what I want to learn
I bring experience with concurrent systems, API contracts, observability and testing at scale, plus a habit of writing down assumptions before arguing about solutions. What I need to learn is the certification workflow itself: how a requirement in a system specification becomes a design, a unit test and a verification case that an auditor can follow, and how tools like DOORS, SCADE or Simulink models fit into that chain at Leonardo. I am not claiming I already know DO-178C. I am saying I want to work in an organisation where that standard is the daily reality, and where a software engineer is expected to understand the aircraft, not just the repository.
That is why Leonardo, rather than aerospace in the abstract. The helicopters division in Yeovil and Pomigliano, the aircraft work on Typhoon and M-346, and the electronics and cyber work in the UK give me a path from general software engineering into safety critical systems without leaving the field I trained in. The work is slower, more constrained and more consequential, and that is exactly the appeal.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13What is the difference between an abstract class and an interface, and when would you choose one over the other?
Reported in Leonardo Software Engineer Interview Questions & Guide 2026
The 90-second answer
Assuming Java, the split is contract versus shared implementation. An interface declares what a type can do and carries no instance state. An abstract class can declare that contract and also carry state, constructors, protected members and concrete code that subclasses reuse. I reach for an interface when unrelated types need to be treated the same way. I reach for an abstract class when I have one family of types that share state or a workflow and differ only in a few steps.
// Java 21
public interface Sensor {
double read(); // implicitly public abstract
default double readAveraged(int samples) {
if (samples <= 0) throw new IllegalArgumentException("samples");
double sum = 0;
for (int i = 0; i < samples; i++) sum += read();
return sum / samples;
}
}
public abstract class BaseSensor implements Sensor {
private final String id; // state an interface cannot hold
protected BaseSensor(String id) { this.id = id; }
public final String id() { return id; }
// Template method: fixes the workflow, leaves read() to subclasses
public final double readAveraged(int samples) {
return Sensor.super.readAveraged(samples);
}
}
public final class TemperatureSensor extends BaseSensor {
public TemperatureSensor(String id) { super(id); }
@Override public double read() { return 21.4; }
}A TemperatureSensor, a PressureSensor and a third party CameraSensor can all be passed where Sensor is expected, even though they share no base class. That is the main reason to prefer an interface for a capability.
| Interface | Abstract class | |
|---|---|---|
| Instance state | None. Fields are public static final constants only | Instance fields, including private and protected |
| Constructors | None | Yes, called via super(...) from subclasses |
| Methods | Abstract by default; default, static and (Java 9+) private allowed | Any access level, concrete or abstract |
| Inheritance | A class can implement many interfaces | A class can extend only one class |
| Instantiation | Never directly | Never directly, but subclasses can be instantiated |
| Adding a method | Breaks existing implementers unless it has a default body | Adding a concrete method is safe; adding an abstract method breaks subclasses |
When I choose each one
Interface first when the type is a role: Comparable, AutoCloseable, a repository, a codec, a listener. The implementers may come from different hierarchies, may be written later, or may be mocks in tests. Small interfaces also keep callers honest. A caller depending on Sensor should not need to know about calibration state or hardware registers.
Abstract class first when the types are variants of one thing. A BaseSensor that owns an id, validates it once in its constructor, and fixes the averaging workflow is a good fit. The subclasses differ in read() and perhaps in a protected hook such as calibrate(). Protected members are the tell: if subclasses need shared access to internal state, an interface cannot express that.
In practice I often combine them, as above: the abstract class implements the interface. Callers program to Sensor. The family shares state and workflow through BaseSensor. A class that needs the capability but does not belong to that family implements Sensor directly.
Failure modes I watch for
A god interface. Once an interface grows to 15 methods, every implementer is forced to stub methods it does not use, and callers cannot tell which methods matter. Split it by capability.
A hierarchy locked by an abstract class. Because Java allows only single class inheritance, extending BaseSensor prevents extending anything else. If a type later needs to join a different family, the abstract class becomes the obstacle. That is why the public contract should stay on the interface.
Breaking evolution. Adding an abstract method to a published interface breaks every external implementer at compile time. A default method avoids that, at the cost of a possibly surprising default behaviour. Adding an abstract method to an abstract class has the same compile break for subclasses, so I add concrete methods with safe defaults there too, or add a new subinterface or subclass.
The interview follow up I expect is about C++. The mechanics map closely: a pure virtual function makes a class abstract in the same way, and a class with only pure virtual functions acts as an interface. The difference is that C++ also allows multiple inheritance of implementation, which Java deliberately avoids to keep the hierarchy unambiguous.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Explain the key differences between the TCP and UDP transport protocols?
Reported in Leonardo Software Engineer Interview Questions & Guide 2026
The 90-second answer
TCP and UDP both sit at the transport layer and carry application data between ports, but they make opposite trade-offs. TCP is a connection-oriented, reliable byte stream. It establishes a session, numbers every byte, retransmits losses, delivers data in order, and slows down when the network signals congestion. UDP is a connectionless datagram service. It sends one packet and moves on, with no delivery guarantee, no ordering, and no congestion control.
That choice decides the failure mode. With TCP, a lost packet stalls later data until the retransmission arrives, so latency spikes but the application sees a clean, complete stream. With UDP, a lost packet is simply gone, so the application sees a gap immediately and must decide whether to tolerate it, fill it, or request it again.
| Property | TCP | UDP |
|---|---|---|
| --- | --- | --- |
| Connection | Three-way handshake (SYN, SYN-ACK, ACK) before data | None, first packet is data |
| Delivery | Acknowledged, retransmitted until delivered or connection fails | Best effort, no acknowledgement |
| Ordering | In-order delivery to the application | Arrival order, may be reordered |
| Duplicates | Suppressed by sequence numbers | Possible, application must handle |
| Congestion control | Yes, window shrinks on loss or delay | None, sender can flood the path |
| Flow control | Receiver window advertises buffer space | None |
| Header size | 20 bytes minimum, up to 60 with options | 8 bytes fixed |
| Data model | Byte stream, message boundaries lost | Datagram, message boundaries preserved |
| Broadcast / multicast | Not supported | Supported |
Overhead in real figures
For a 100-byte payload, IP adds 20 bytes. TCP adds at least 20 more, so 140 bytes on the wire. UDP adds 8, so 128 bytes. That 9% difference matters little for bulk transfer. It matters for small, frequent packets. A 20-byte sensor reading sent 50 times per second costs 60 bytes of headers per packet over TCP/IP against 28 over UDP/IP. At that rate the header alone is 24,000 bytes per second against 11,200. The bigger cost with TCP is not the header. It is the handshake round trip before the first byte, and head-of-line blocking after a loss.
Worked trace: one packet lost
Assume a sender transmits segments 1, 2, 3 and segment 2 is dropped.
| Time | TCP behaviour | UDP behaviour |
|---|---|---|
| t0 | Sends 1, 2, 3 | Sends datagrams 1, 2, 3 |
| t1 | Receiver gets 1 and 3, buffers 3, sends duplicate ACK for 1 | Receiver gets 1 and 3, delivers both to the application |
| t2 | Sender sees duplicate ACKs, retransmits 2 | Nothing happens, datagram 2 is lost |
| t3 | Receiver gets 2, delivers 2 then buffered 3 | Application has a permanent gap at 2 |
TCP therefore trades a latency spike for completeness. UDP trades completeness for steady latency. For live telemetry from a drone fleet, a missing sample is usually less harmful than a 500 ms stall waiting for it, so UDP plus a sequence number in the payload lets the receiver count gaps. For a firmware image or a payment record, the opposite holds, and TCP is the default.
Code makes the contract visible
# Python 3.12, checked against CPython socket API
import socket
# TCP: connect first, stream semantics, close signals end of stream
with socket.create_connection(("telemetry.example", 9000), timeout=2) as s:
s.sendall(b"frame-1042")
s.shutdown(socket.SHUT_WR)
# UDP: no connect, each sendto is one datagram, no delivery promise
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(0.2)
s.sendto(b"frame-1042", ("telemetry.example", 9000))Note the API difference. create_connection and sendall hide retransmission and ordering. sendto exposes the datagram boundary and returns as soon as the packet is queued, not when it arrives.
When not to use the obvious choice
UDP is not automatically faster end to end. Without congestion control, a UDP sender blasting at line rate can cause loss for itself and for TCP flows sharing the link, and its own throughput collapses. Modern protocols such as QUIC run over UDP precisely to get datagram transport while reimplementing reliability, ordering and congestion control in user space, which shows the real decision is which guarantees you need and where you implement them. Conversely, TCP is a poor fit for request-response patterns where a single lost packet delays a fresh answer that would have superseded it, which is why DNS uses UDP for queries and falls back to TCP for large responses, and why media calls prefer UDP with jitter buffers and loss concealment over a reliable stream.
A strong close in the interview: name the guarantee first, then the mechanism that provides it, then the cost. Reliability costs latency and head-of-line blocking. Low latency costs application-level recovery. That framing answers the comparison and shows how you would pick for a given system.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15When would equality testing between two floating-point numbers fail, and how do you handle it?
Reported in Leonardo Software Engineer Interview Questions & Guide 2026
The 90-second answer
Direct == on floats fails when two values that should represent the same real number arrive through different computations, or when the decimal value you expect has no exact binary representation. The classic case is 0.1 + 0.2 == 0.3 returning False in Python, Java, C++ and JavaScript. IEEE 754 binary floating point stores numbers as a binary fraction with a 53-bit mantissa for double, so 0.1 is stored as the closest binary approximation, slightly above or below the true decimal. Adding two approximations compounds that error, and the result lands one or more units in the last place away from the approximation of 0.3.
That is only one failure mode. Repeated accumulation makes it worse: summing 0.1 ten times in a loop, or adding many small sensor readings, drifts further from the mathematically expected total. Catastrophic cancellation does the opposite damage. Subtracting two nearly equal large numbers leaves a small result whose relative error is huge. Two algebraically equivalent formulas can also disagree, for example sqrt(x*x + y*y) versus a scaled computation, because each rounding step differs. Special values break intuition too: NaN == NaN is False by design, while -0.0 == 0.0 is True even though their bit patterns differ.
| Computation | Stored result (Python, double) | == expected value |
|---|---|---|
0.1 + 0.2 | 0.30000000000000004 | False against 0.3 |
sum([0.1] * 10) | 0.9999999999999999 | False against 1.0 |
1e16 + 1.0 | 1e16 | True against 1e16, the 1.0 is lost |
float('nan') | nan | False against itself |
Exact equality is still correct in some cases. Comparing a value against itself after the same computation, checking integers up to 2^53 exactly representable in a double, or testing a parsed flag or sentinel all work reliably. The problem is expecting exact equality across different arithmetic paths or against a decimal literal.
How I handle it
First, decide whether the domain needs exactness. For money, billing quantities, or protocol fields where a cent or a count must match, I avoid binary floats entirely. I use integer minor units or Decimal with an explicit rounding mode, and compare exactly.
For measured or computed quantities, such as positions, sensor readings, or telemetry derived from two flight paths, I compare with a tolerance that scales with magnitude. A fixed epsilon like 1e-9 is too strict for values around 1e12 and too loose for values around 1e-12. Relative tolerance handles scale, absolute tolerance handles values near zero.
import math
def close(a: float, b: float) -> bool:
# rel_tol scales with magnitude; abs_tol covers the near-zero case
return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)
close(0.1 + 0.2, 0.3) # True
close(1e16 + 1.0, 1e16) # True, difference is below one ulp at that scale
math.isnan(float('nan')) # check NaN explicitly, isclose returns False for NaNIn C++ the equivalent is std::abs(a - b) <= std::max(abs_tol, rel_tol * max(abs(a), abs(b))), which is what std::isclose style helpers implement. I pick the tolerances from the domain, not from habit. If the sensor resolution is 0.01 m, a tolerance of 1e-6 m claims precision the hardware cannot deliver, and a tolerance of 1 m would hide a real divergence between two computed tracks.
Second, reduce the error at the source where it matters. Summing many values with Kahan summation or math.fsum in Python keeps the running error near one rounding instead of growing with the count. Sorting or pairwise summation helps for large arrays. Reformulating a formula to avoid cancellation, such as using hypot(x, y) instead of sqrt(x*x + y*y) for large values, prevents overflow and intermediate rounding.
Third, handle the edges explicitly. Check isnan before any equality or ordering logic, because NaN poisons comparisons and sorting. Treat -0.0 and 0.0 as equal for numeric purposes, and only distinguish them if sign matters for output formatting. For thresholds, compare with <= against a tolerance band rather than testing for a hit on an exact value, and log the actual difference when a check fails so the tolerance can be tuned from data instead of guessed.
In tests I use an approximate assertion with the same tolerances as production code, so a test failure means the values diverged beyond the domain tolerance, not that binary rounding moved the last bit.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16What is the Fourier Transform, and how is it applied in signal processing applications?
Reported in Leonardo Software Engineer Interview Questions & Guide 2026
The 90-second answer
The Fourier Transform re-expresses a signal as a sum of sinusoids. Instead of describing voltage, vibration or a radar return as a function of time, you describe how much of each frequency it contains, and with what phase. That change of basis is useful because many physical operations are simple in one domain and messy in the other. Filtering, detecting a tone buried in noise, and compressing a waveform all become operations on frequency bins.
For a continuous signal x(t), the transform is:
X(f) = integral over t of x(t) * exp(-j2pift) dt
In software you almost never compute that integral. You sample the signal at Fs samples per second, take N samples, and compute the Discrete Fourier Transform (DFT). The FFT is the fast algorithm for that DFT, reducing O(N^2) to O(N log N). A candidate should be able to say which one they mean, because the interviewer will ask.
Worked trace: what the bins mean
Take Fs = 8 Hz and N = 8 samples of a pure 1 Hz cosine, sampled at t = 0, 1/8, 2/8, ... The DFT has bins k = 0..7 at frequencies k*Fs/N = 0, 1, 2, 3, 4, 5, 6, 7 Hz. Only bin 1 (and its mirror, bin 7, because the signal is real) is non-zero. That is the whole idea in miniature: a tone in time becomes a spike in frequency.
| Bin k | Frequency | Magnitude for 1 Hz cosine | Interpretation |
|---|---|---|---|
| 0 | 0 Hz | 0 | no DC offset |
| 1 | 1 Hz | 4.0 | the tone itself |
| 2 | 2 Hz | 0 | no harmonic |
| 3 | 3 Hz | 0 | no harmonic |
| 4 | 4 Hz | 0 | Nyquist bin, Fs/2 |
| 5-7 | 5-7 Hz | 0 | mirror of bins 3-1 for real input |
If you add a second tone at 3 Hz with half the amplitude, bin 3 appears at magnitude 2.0 and nothing else changes. That linearity is why spectral analysis works: components add in frequency just as they add in time.
Code: FFT on a real capture
Checked against Python 3.11 with NumPy 1.26. This is the pattern used for vibration monitoring on rotating machinery and for audio front ends.
import numpy as np
Fs = 48_000 # sample rate, Hz
N = 4096 # FFT size, power of two
t = np.arange(N) / Fs
x = np.cos(2 * np.pi * 440 * t) + 0.5 * np.cos(2 * np.pi * 1200 * t)
x += 0.05 * np.random.default_rng(0).normal(size=N) # noise floor
X = np.fft.rfft(x * np.hanning(N)) # window to reduce spectral leakage
freqs = np.fft.rfftfreq(N, d=1 / Fs)
mags = np.abs(X)
peaks = np.argsort(mags)[-2:][::-1]
for k in peaks:
print(f"{freqs[k]:.1f} Hz magnitude {mags[k]:.1f}")
# 440.0 Hz and 1200.0 Hz, within one binFrequency resolution is Fs/N, here 48000/4096 = 11.7 Hz. You cannot separate two tones closer than about one bin without zero padding or a longer window, and zero padding interpolates the spectrum rather than adding information. The capture itself takes N/Fs = 85 ms, which sets a hard floor on detection latency before any processing runs.
Where it is applied, and where it is not
| Task | Why frequency domain helps | Practical detail |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Filtering | A low-pass filter zeroes or attenuates high bins, then inverse FFT returns time domain | Multiply in frequency, one inverse FFT. Equivalent FIR in time can need thousands of taps for a sharp cutoff. |
| Spectral analysis | Bearing faults, rotor imbalance and mains hum show as peaks at characteristic frequencies | Compare peak bins against a baseline spectrum, not an absolute threshold. |
| Convolution | Convolution in time becomes multiplication in frequency | FFT convolution wins once the filter length exceeds roughly 64 taps. |
| Compression | Energy concentrates in few bins, so small bins can be quantized coarsely | JPEG and MP3 use DCT variants of the same idea, block by block. |
| Modulation and radar | Carrier, Doppler shift and chirp are defined by frequency content | Doppler processing in pulse-Doppler radar is an FFT across pulses in a coherent interval. |
The failure mode to name in an interview is non-stationarity. A plain FFT assumes the signal statistics hold across the whole window. A chirp, a transient impact, or a tone that starts halfway through the window smears across bins and the peak tells you little about when it happened. The fix is the Short-Time Fourier Transform: window the signal into overlapping segments, FFT each one, and keep a spectrogram of magnitude over time and frequency. You trade frequency resolution for time resolution, governed by window length. A 4096-sample window at 48 kHz gives 11.7 Hz resolution but only localises events to about 85 ms. A 256-sample window localises to 5 ms but resolution degrades to 187 Hz.
Two other traps come up in practice. Aliasing: any content above Fs/2 folds back into the band and looks like a real tone, so an anti-alias filter before sampling is not optional. Leakage: a tone that does not complete an integer number of cycles in the window spreads into neighbouring bins, which is why the code above applies a Hann window. Windowing widens the main lobe, so peaks get broader, in exchange for much lower sidelobes.
| Method | Cost for N points | What you get | When to pick it |
|---|---|---|---|
| --- | --- | --- | --- |
| DFT | O(N^2) | exact bins | teaching, tiny N, arbitrary frequencies |
| FFT | O(N log N) | same bins as DFT | default for sampled signals, N a power of two or smooth composite |
| STFT | O(M * N log N) for M windows | time-frequency map | transients, speech, chirps, any non-stationary signal |
For N = 4096, the DFT needs about 16.7 million complex multiply-adds and the FFT about 49 thousand, a factor of roughly 340. That gap is the difference between offline analysis and running on an embedded processor at frame rate.
If the interviewer pushes on implementation, mention that real-input FFTs (rfft) exploit conjugate symmetry to halve the work, that fixed-point FFTs in avionics hardware need scaling at each stage to avoid overflow, and that phase matters when you reconstruct a signal with the inverse transform, even though magnitude alone is enough for peak detection.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17How does a Kalman filter work, and in what scenarios would you implement one for tracking or navigation?
Reported in Leonardo Software Engineer Interview Questions & Guide 2026
The 90-second answer
A Kalman filter is a recursive estimator for a hidden state that evolves over time and is observed through noisy sensors. It keeps two things: a state estimate, for example position and velocity, and a covariance matrix P that says how uncertain that estimate is. Each cycle has a predict step and an update step.
Predict uses the motion model to advance the estimate and grow its uncertainty. Update compares the new measurement against the prediction and blends the two, weighted by their relative uncertainty. That weighting is the Kalman gain K. A trusted sensor gets a high gain, a noisy one gets a low gain, and the covariance shrinks after a good update.
For a linear system with Gaussian noise:
x = F x + B u # predict state
P = F P F^T + Q # predict covariance
K = P H^T (H P H^T + R)^-1 # Kalman gain
y = z - H x # innovation: measurement minus prediction
x = x + K y # update state
P = (I - K H) P # update covarianceF is the state transition, H maps state to measurement, Q is process noise (how much the model itself can be wrong), and R is measurement noise (how much the sensor can be wrong). In practice Q and R are tuned from sensor data sheets and flight test logs, not guessed.
Worked trace, 1D position
Hypothetical numbers, random-walk model with F = 1, H = 1:
| Step | Prior x, P | Measurement z, R | Gain K = P/(P+R) | Posterior x, P |
|---|---|---|---|---|
| 1 | 0.0, 1.0 | 2.0, 1.0 | 0.50 | 1.00, 0.50 |
2, after Q = 0.1 | 1.0, 0.60 | 2.4, 1.0 | 0.375 | 1.53, 0.375 |
The estimate moves toward the measurement but never jumps to it, because R says the sensor is noisy. If the next measurement is missing, the filter just predicts and P grows by Q each step, which is exactly the behaviour you want during a GPS dropout.
Where I would use it at Leonardo
The classic case is sensor fusion for navigation. An IMU gives high-rate acceleration and angular rate, so it is smooth over short intervals, but it drifts. GPS gives absolute position at 1 to 10 Hz with metre-level noise and occasional jumps. A Kalman filter, usually in constant-velocity or constant-turn form, fuses the two and outputs position, velocity and a covariance the flight software can use to decide whether the fix is trustworthy.
Other cases I would reach for it: radar or ADS-B target tracking where detections are intermittent and you need velocity, not just position; drone fleet localisation where vision, UWB ranging and IMU have different rates and noise profiles; and any tracking problem where you must estimate a quantity you cannot measure directly, such as velocity from position-only sensors.
# Constant-velocity filter, checked against NumPy 1.26
import numpy as np
F = np.array([[1.0, 1.0], [0.0, 1.0]]) # dt = 1 s
H = np.array([[1.0, 0.0]]) # GPS measures position only
Q = np.diag([0.01, 0.05])
R = np.array([[4.0]]) # GPS std dev = 2 m
x = np.array([0.0, 0.0])
P = np.eye(2) * 10.0
for z in [2.1, 3.8, 6.2]: # noisy position fixes
x = F @ x
P = F @ P @ F.T + Q
K = P @ H.T @ np.linalg.inv(H @ P @ H.T + R)
x = x + K @ (z - H @ x)
P = (np.eye(2) - K @ H) @ P
print(f"pos={x[0]:.2f} vel={x[1]:.2f} P_pos={P[0,0]:.2f}")The velocity estimate emerges even though no sensor measures it. That is the main payoff over a simple low-pass filter.
When I would not use the plain version
| Approach | Use it when | Watch out for |
|---|---|---|
| Kalman | Linear motion, Gaussian noise, fixed state dimension | Diverges if Q is set too small and the model is wrong |
| Extended Kalman (EKF) | Mildly nonlinear, for example GPS pseudorange or polar radar | Linearisation error, Jacobian mistakes, needs care at singularities |
| Unscented Kalman (UKF) | Stronger nonlinearity, often better than EKF with similar cost | More tuning, sigma points must stay valid |
| Particle filter | Multimodal or heavily non-Gaussian, for example ambiguous data association | Cost grows with state dimension, sample degeneracy |
| Complementary or simple averaging | One dominant sensor, tight compute budget, no need for covariance | No principled uncertainty, drifts silently |
Failure modes I would test for
Divergence is the big one. If Q is too small, the filter becomes overconfident, P collapses, and it ignores new measurements. If R is too small, it chases GPS noise and multipath jumps. I would log the innovation y and its normalised squared value. A sustained large innovation means the model or the sensor has changed, not that the state suddenly moved.
Outliers need gating. A GPS fix 200 m away during multipath should be rejected if its Mahalanobis distance exceeds a threshold, rather than blended in. Timestamp alignment matters just as much: fusing an IMU sample stamped 50 ms late with a GPS fix as if they were simultaneous biases the velocity estimate, and at aircraft speeds that is metres of error.
So in an interview I would frame it as: use a Kalman filter when you have a decent motion model, noisy asynchronous sensors, and you need both an estimate and a defensible uncertainty for it. If the motion is nonlinear, extend it. If the noise is multimodal, switch families. And always instrument the innovation, because that is where the filter tells you it has stopped believing its own model.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18How do secure development practices fit into the overall product life cycle?
Reported in Leonardo Software Engineer Interview Questions & Guide 2026
The 90-second answer
Secure development is a set of gates, artefacts and ownership that run from requirements to decommissioning. At Leonardo that span is the point. A helicopter, aircraft or drone system may stay in service for 20 to 30 years under airworthiness certification, so a vulnerability found in year 12 has to be patchable without invalidating the safety case. That constraint shapes every phase below.
| Phase | Practice that belongs there | Artefact or gate that proves it | Cost if skipped |
|---|---|---|---|
| Concept | Security requirements alongside functional ones, abuse cases, data classification | Requirements traceability matrix, including secure boot and signed update requirements | A design that cannot be patched later without hardware change |
| Design | Threat modelling per data flow, trust boundaries, key management design | Threat model with mitigations traced to requirements, reviewed before code | Encryption added late, usually in the wrong layer |
| Implementation | Coding standard, peer review, secrets handling, pinned dependencies | Reviewed pull requests, no long-lived credentials in the repo | Secrets in history, unpatched libraries shipped in COTS components |
| Verification | SAST, SCA, fuzzing of parsers, penetration test on the release candidate | Scan reports triaged by severity, test evidence for the certification file | Findings arrive after the design is frozen, when fixes are expensive |
| Release | SBOM generation, reproducible build, artifact signing | Signed SBOM and build provenance attached to the release | You cannot answer which fleet units contain a vulnerable component |
| Operations | Vulnerability disclosure intake, coordinated patching, fleet telemetry | Patch SLA by severity, signed update path tested on a rig | A critical CVE waits for the next scheduled maintenance window |
| Retirement | Key revocation, data sanitisation, decommissioning plan | Revoked certificates, wiped keys, archived SBOM | Retired units still trust a compromised signing key |
Where the trade-offs bite
Shift-left works only if the gates are cheap enough to run on every pull request. A SAST run that takes 4 minutes on a 200k-line service is acceptable in CI. A full penetration test is not, so it runs on the release candidate and on major architecture changes. The same logic applies to dependency scanning. Blocking a build on every CVE creates alert fatigue, because many findings have no exploit path in your configuration. Blocking on critical, exploitable findings with a fix available keeps the gate credible.
# ci/check_sbom.py, run after the build and before signing
import json
import sys
sbom = json.load(open("sbom.json"))
blocking = [
c for c in sbom["components"]
if c.get("severity") == "CRITICAL"
and c.get("exploitable")
and c.get("fix_available")
]
for c in blocking:
print(f"BLOCK {c['name']} {c['version']} {c['cve']}")
sys.exit(1 if blocking else 0)Arithmetic helps set the threshold. Suppose 60 services each ship monthly and each carries 300 components. That is 18,000 component instances to track. Without an SBOM per release, answering a single CVE query means rebuilding that inventory by hand, which takes days. With signed SBOMs, the same query is a grep across release artefacts and finishes in minutes. The SBOM is therefore an operational tool, not a compliance document.
Failure modes I watch for
Threat modelling done once at project start and never updated. The system gains a maintenance laptop interface in year three, and that new trust boundary has no model. Detection: every architecture change requires a threat model delta as a merge requirement.
Scanner output nobody owns. SAST findings accumulate because no team is measured on reducing them. Detection: track critical findings older than 30 days per service, reviewed in the same forum as reliability errors.
Patching that breaks certification. A security fix changes code in a DO-178C DAL A module, and the team discovers the recertification cost only after the CVE is public. Detection: maintain a pre-agreed patch path for security fixes, with regression tests and evidence templates ready before an incident.
Key compromise with no revocation plan. Signing keys for firmware updates live for the life of the fleet. Detection: test key rotation and revocation on a ground rig at least annually, and keep an offline root key separate from the online signing key.
In an interview I would close on ownership. Security practices fit the life cycle when each phase produces evidence the next phase can use, and when someone is accountable for the patch path in year 12, not only for the release in month 6.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Code a function that reads a string and determines whether that string is a palindrome?
Reported in Leonardo DRS Software Engineer interview questions & guide 2026
The 90-second answer
I would ask one clarifying question before coding: is this an exact palindrome, where case and punctuation count, or a normalized one, where "Racecar" and "A man, a plan, a canal: Panama" count? In an interview I would state my assumption, code the exact version first because it is the literal question, then show the normalized variant as a one line change to the comparison.
For the exact version I use two pointers moving inward. That is O(n) time and O(1) extra space, and it stops at the first mismatch instead of building a reversed copy.
# Python 3.11
def is_palindrome(s: str) -> bool:
if not isinstance(s, str):
raise TypeError("expected str")
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return TrueEmpty string and single character return True. That follows the definition: no mismatched pair exists. If the caller passes None in a typed codebase, the type checker should reject it before runtime. Raising here makes a programming error visible instead of silently returning a boolean the caller might trust.
Worked trace
For s = "abca", indices 0 to 3:
| Step | i | j | s[i] | s[j] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 3 | a | a | match, move both |
| 2 | 1 | 2 | b | c | mismatch, return False |
For "racecar" the pointers meet at the centre e with i == j, the loop ends, and the function returns True.
Normalized variant
Most follow ups mean ignore case, spaces and punctuation. I would not preprocess into a new string if memory matters. I would advance each pointer past characters that are not alphanumeric, then compare casefold() values. casefold() handles cases like German ß better than lower() for caseless matching.
def is_palindrome_normalized(s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].casefold() != s[j].casefold():
return False
i += 1
j -= 1
return TrueThat still runs in O(n) time and O(1) extra space. The trade off is that isalnum() and casefold() are Unicode aware, so behaviour depends on the Unicode version in the runtime. For a 10 million character input, the reversed copy approach (s == s[::-1]) allocates roughly another 10 MB for the copy plus the slice overhead, while two pointers allocate nothing beyond the input. On short strings the reversed version is shorter to write and often fast enough in CPython because the reversal is implemented in C, which is a fair point to raise if the interviewer values brevity over allocation.
Failure modes I would name
Recursion looks clean but risks hitting the recursion limit on long inputs, around 1,000 frames by default in CPython, and adds call overhead per character. Unicode grapheme clusters are a subtler trap: a string with combining accents or emoji made of multiple code points can be a visual palindrome while failing a code point comparison. If that matters, the correct fix is to normalize to NFC form first with unicodedata.normalize("NFC", s) and compare grapheme clusters, not code points. I would mention that only if the interviewer pushes on Unicode, since it changes the complexity and the library dependency.
I would close by stating the contract I coded to: exact match, empty string is a palindrome, non string input raises, O(n) time, O(1) space.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Explain the key differences between a Process and a Thread?
Reported in Leonardo DRS Software Engineer interview questions & guide 2026
The 90-second answer
A process is a unit of resource ownership. A thread is a unit of scheduling inside a process. That one sentence predicts almost every other difference.
A process has its own virtual address space, file descriptor table, signal mask, and credentials. The kernel can schedule it, protect it, and kill it independently. A thread shares all of that with its siblings and has only its own stack, registers, program counter, and thread-local storage. The kernel schedules threads, not processes, on Linux. A process is really a container that holds at least one thread.
| Dimension | Process | Thread |
|---|---|---|
| --- | --- | --- |
| Address space | Private, isolated by the MMU | Shared with all threads in the process |
| Creation cost | fork() copies the page tables, typically 1 to 10 ms for a large process, less with copy-on-write | pthread_create() allocates a stack, typically 10 to 50 microseconds |
| Communication | Explicit IPC: pipes, sockets, shared memory, signals | Direct shared memory, needs locks or atomics |
| Failure | A segfault in one process does not corrupt another | A segfault, stack overflow, or heap corruption in one thread kills the whole process |
| Scheduling | Kernel schedules its threads | Same, with a TID on Linux |
| Resource limits | Counted per process: memory, open files, CPU time | Counted per process, so one thread can exhaust the pool for all |
Why the isolation exists
The MMU gives each process a separate page table. Thread 1 in Process A can only touch pages mapped into that table. That is why a crash in a telemetry parser process cannot scribble over a flight control process if they are separate processes, even on the same core. Threads in one process see the same page table, so a stray write in one thread is visible to all of them. That sharing is the performance win and the hazard.
Creation cost follows from the same mechanism. fork() must build a new page table and copy the descriptor table, even though copy-on-write defers copying data pages until they are written. pthread_create() only needs a new stack and a kernel task struct. In a worked example, spawning 1,000 threads for a sensor fan-out might take about 30 ms and roughly 8 MB of virtual stack space at the default 8 MB per stack, while spawning 1,000 processes would take seconds and far more memory. The arithmetic flips if the work is CPU bound in Python, where the GIL means threads do not use multiple cores for pure Python code. Processes do, at the cost of IPC.
// Checked against Linux with glibc and pthreads.
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
void *worker(void *arg) {
// Shares heap, globals, and file descriptors with main.
// A crash here terminates the whole process.
return NULL;
}
int main(void) {
pthread_t tid;
pthread_create(&tid, NULL, worker, NULL);
pthread_join(tid, NULL);
pid_t pid = fork(); // New address space, copy-on-write.
if (pid == 0) {
// Child process: separate heap and descriptors.
_exit(0);
}
return 0;
}Choosing between them
Use threads when the work shares state constantly and the failure domain can be the whole program. A drone fleet monitor that reads sensor buffers, updates a shared track list, and writes to a display is a natural fit: one process, a thread per sensor stream, locks around the shared list.
Use processes when you need a fault or security boundary. On an aircraft software partition, I would put an untrusted parser or a third-party codec in its own process so a malformed input cannot take down the control loop, and communicate over a pipe or shared memory ring with a fixed message size. The supervisor can restart that process, check its exit code, and log the crash without restarting the rest.
Two failure modes interviewers probe. First, deadlock: threads sharing memory can wait on each other forever, and the process looks alive while doing nothing. Detection is a watchdog that checks progress counters, not just CPU use. Second, resource exhaustion: a thread leak that creates threads without joining them will hit pthread_create() failure with EAGAIN long before memory runs out, because each thread holds a stack. The fix is a bounded thread pool, sized from measured latency. If p99 latency rises once the pool saturates at, say, 32 workers, that is the signal to add workers or move to processes, not to raise the limit blindly.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21What mechanisms are used for thread synchronization, and how do you prevent race conditions or deadlocks?
Reported in Leonardo DRS Software Engineer interview questions & guide 2026
The 90-second answer
I pick the mechanism from the invariant I need to protect, not from habit. For mutual exclusion around a short critical section I use a mutex, in Java ReentrantLock or in C++ std::mutex. For a read-heavy shared structure I use a read-write lock. For waiting on a state change I use a condition variable paired with that lock. For a counter or flag that never needs to block I use an atomic with compare-and-swap. I prevent races by making the check and the update atomic, and I prevent deadlocks by imposing a global lock order, never holding a lock while blocking on I/O, and using timed acquisition where a lock order cannot be guaranteed.
That framing matters on an aircraft or drone system at Leonardo, where a telemetry thread, a control thread and a logging thread may share a buffer. A race there is not a lost update in a web request. It is a torn frame read by the control loop.
Mechanisms and when each fits
| Mechanism | Use it for | Cost and limit |
|---|---|---|
Mutex / ReentrantLock | Short critical section, compound invariant | Blocks the holder's peers. Priority inversion is possible if a low-priority thread holds it while a high-priority thread waits. |
ReadWriteLock | Many readers, few writers, for example a configuration table | Writers starve if readers keep arriving. Some implementations favour writers to avoid that. |
Condition / ConditionVariable | Wait until queue not empty or shutdown requested | Must be used in a loop. A spurious wakeup or a notify sent before the wait would otherwise lose the signal. |
Semaphore | Bounding a pool, for example 20 concurrent downlink sessions | Does not enforce ownership. Any thread can release it, so it cannot protect an invariant the way a mutex can. |
Atomic / CAS | Counter, flag, reference swap | Only works for a single word or a pointer. It cannot make a multi-field update atomic. |
| Lock-free queue | Producer-consumer handoff between real-time threads | Harder to verify. ABA on a reused node is a real failure mode if nodes are recycled. |
A volatile flag in Java, or std::atomic<bool> in C++, gives visibility. It does not give atomicity for count++. That increment is a read, an add and a write, and two threads can interleave it.
// Java 17. Checked against the OpenJDK 17 API.
import java.util.concurrent.locks.ReentrantLock;
final class FrameBuffer {
private final ReentrantLock lock = new ReentrantLock();
private byte[] frame;
private long sequence;
void publish(byte[] next, long seq) {
lock.lock();
try {
frame = next;
sequence = seq; // both fields change under the same lock
} finally {
lock.unlock();
}
}
byte[] snapshot() {
lock.lock();
try {
return frame == null ? null : frame.clone();
} finally {
lock.unlock();
}
}
}The clone matters. Returning the internal array would let the caller mutate it after the lock is released, which reintroduces the race through the back door.
Race conditions: a concrete trace
Two threads increment a shared counter without synchronisation. The counter starts at 10.
| Step | Thread A | Thread B | Counter in memory |
|---|---|---|---|
| 1 | read 10 into register | 10 | |
| 2 | read 10 into register | 10 | |
| 3 | write 11 | 11 | |
| 4 | write 11 | 11 |
Two increments produced one. With an atomic incrementAndGet() the read-modify-write is a single CAS loop in hardware, so step 2 cannot observe the stale value. With a lock, the second thread cannot enter the section until the first leaves it.
Deadlocks: prevention, not recovery
A deadlock needs four conditions at once: mutual exclusion, hold and wait, no preemption, and a circular wait. I break circular wait with a lock hierarchy. Every lock gets a rank, and code may only acquire locks in increasing rank order. If a function needs locks out of order, it releases what it holds and retries, or it takes them in the correct order up front.
Trace of the failure this prevents. Thread 1 takes bufferLock then waits for logLock. Thread 2 takes logLock then waits for bufferLock. Neither can proceed, and neither will time out on its own. With ranks, say bufferLock is rank 1 and logLock is rank 2, thread 2 must take bufferLock first, so the cycle cannot form.
Where a strict order is impossible, for example two subsystems each owning a lock and each needing the other's, I use tryLock with a timeout and back off with jitter, then retry in rank order. A timeout alone is not a fix. If the code simply proceeds without the lock, the deadlock becomes a race.
Detection is the last line. In production I watch lock hold times and thread dumps for cycles, and in tests I run with lock-order checking or ThreadSanitizer, which flags unsynchronised accesses and lock-order inversions before they reach flight software. The rule I apply in review is simple: if a diff adds a lock acquisition inside a section that already holds one, I ask for the rank of the new lock and for proof that no path acquires them in the opposite order.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22What is your experience with the full software development lifecycle (SDLC) within a highly regulated environment?
Reported in SDLC in Regulated Environments
The 90-second answer
In a regulated programme I treat the SDLC as a controlled chain from a safety or security need to a released baseline, where every artefact can be traced forward and backward. At Leonardo that usually means ARP4754A for the system and DO-178C for airborne software, with the Design Assurance Level set by the failure condition. A DAL B function, for example, needs independence between design and verification, bidirectional traceability, and structural coverage evidence that a DAL C function can satisfy with less rigour. The same discipline applies to ground systems under IEC 61508 or ISO 26262, and to security under DO-326A, but the DAL drives the depth of evidence.
The lifecycle I have run looks like this:
Requirements are written to be testable, each with a unique ID, a rationale, and a safety allocation. Design artefacts reference those IDs. Code references design IDs in headers. Test cases reference requirements, not code, so a change in implementation does not silently rewrite the pass criteria. A traceability matrix is generated from the requirements tool, not maintained by hand in a spreadsheet, and a gap in either direction blocks the baseline.
| Artefact | Trace link | Evidence at release |
|---|---|---|
| SYS-042: inhibit thrust reverser above 120 kt | SW-118, DES-031 | Analysis plus test TC-204 |
| SW-118: reverser command logic | DES-031, SRC-077 | Unit test, MC/DC 100% for DAL B |
| DES-031: state machine, 4 states | SRC-077, TC-204 | Review record, coverage report |
| TC-204: boundary at 119, 120, 121 kt | SYS-042 | Pass/fail log on qualified rig |
Verification is not testing alone. For DAL A and B I plan structural coverage from the start. Modified Condition/Decision Coverage at 100% is the usual bar for DAL A, and decision coverage for DAL B, measured on the compiled object code where the standard requires it. A branch that never executes in the test suite is treated as a defect, not as dead code to ignore, because it may hide an unintended function. I have used a small script in CI to fail the build when the trace export contains an orphan:
# Python 3.11, checked against DO-178C trace exports
import csv, sys
reqs = {r["id"] for r in csv.DictReader(open("requirements.csv"))}
tests = {r["req_id"] for r in csv.DictReader(open("tests.csv"))}
orphans = sorted(reqs - tests)
if orphans:
sys.exit(f"Unverified requirements: {', '.join(orphans)}")That check runs on every commit, not only at audit time. Waiting until the Statement of Inspection to discover 40 untraced requirements means re-verification of everything downstream.
Configuration and change control decide whether the evidence means anything. Every artefact lives in version control with a baseline tag. A change request goes to the Change Control Board, which assesses safety impact, re-runs the affected verification, and updates the trace matrix before the new baseline is approved. Tools that can affect the output, such as a compiler or a requirements tool, are qualified under DO-330 or their use is justified, and the tool versions are recorded in the build log. Problem reports stay open until the fix is verified and the regression suite passes, and a fix in a DAL B component triggers impact analysis on anything that depends on it.
Failure modes I have seen, and how they surface. A late requirement change, for example a new inhibit condition, invalidates tests that were written against the old wording. The trace matrix shows it immediately because the requirement version changes and the linked tests are flagged stale. A second failure is verification by the author. Independence is not a formality. When the same person writes the code and signs off the test, review comments drop and coverage gaps hide in plain sight. A third is tool drift, where a developer upgrades a local compiler and the coverage numbers no longer match the qualified build. Pinning the toolchain in the build environment and recording its version in the release record prevents that.
When an interviewer asks what I would do differently, my answer is to start the trace and coverage planning in the first sprint, not after code exists. In a regulated environment speed comes from never having to reconstruct evidence, not from skipping it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23Describe a time you had to implement a specific protocol or interface between software and a physical sensor?
Reported in Sensor Protocol and Interfaces
The 90-second answer
I implemented an I2C driver for an MPU-9250 IMU on a vibration test rig, reading acceleration and temperature at 200 Hz into a Linux userspace logger. The rig needed to correlate vibration with motor RPM, so timing jitter mattered more than raw throughput. I chose I2C over SPI and UART for that board because the sensor sat 30 cm from the controller on a shared bus with a temperature sensor, and I2C gave me addressing and clock stretching without extra chip-select lines.
| Bus | Wiring | Speed used | Why I did or did not use it |
|---|---|---|---|
| I2C | 2 wires, shared | 100 kHz standard mode | Addressed devices, clock stretching, short run |
| SPI | 4 wires per device | 10 MHz typical | Faster, but one chip-select per device and no in-band ACK |
| UART | 2 wires, point to point | 115200 baud | Simple, but no addressing and no flow control by default |
The sensor used 7-bit address 0x68, with AD0 tied low. I probed it first with i2cdetect and a logic analyser, then wrote the driver in C against i2c-dev so the same register logic could move to a bare-metal port later.
// C11, Linux i2c-dev, checked against kernel 6.8 headers
#include <linux/i2c.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#define IMU_ADDR 0x68
#define REG_WHO_AM_I 0x75
#define REG_ACCEL_XOUT_H 0x3B
#define LSB_PER_G 16384.0f
static int read_regs(int fd, uint8_t reg, uint8_t *buf, int len) {
struct i2c_msg msgs[2] = {
{ .addr = IMU_ADDR, .flags = 0, .len = 1, .buf = ® },
{ .addr = IMU_ADDR, .flags = I2C_M_RD, .len = len, .buf = buf },
};
struct i2c_rdwr_ioctl_data data = { .msgs = msgs, .nmsgs = 2 };
return ioctl(fd, I2C_RDWR, &data);
}
int read_accel_g(int fd, float *x_g) {
uint8_t raw[6];
if (read_regs(fd, REG_ACCEL_XOUT_H, raw, 6) < 0) return -1;
int16_t v = (int16_t)((raw[0] << 8) | raw[1]);
*x_g = (float)v / LSB_PER_G;
return 0;
}A single read is a repeated-start transaction. The worked trace from the analyser, at 100 kHz, looked like this:
| Step | Bus action | Bytes on wire | Meaning |
|---|---|---|---|
| 1 | START | S | Controller takes bus |
| 2 | Address + write | 0xD0 + ACK | 0x68 << 1, R/W = 0 |
| 3 | Register pointer | 0x3B + ACK | Start at ACCEL_XOUT_H, auto-increment on |
| 4 | Repeated START | Sr | Change direction without releasing bus |
| 5 | Address + read | 0xD1 + ACK | R/W = 1 |
| 6 | Data | 6 bytes, ACK on first 5, NACK on last | X, Y, Z high/low pairs |
| 7 | STOP | P | Release bus |
That trace caught a bug early. My first version issued a STOP between steps 3 and 5. The sensor accepted the pointer but dropped it on STOP, so every read returned the WHO_AM_I register instead of acceleration. The repeated start fixed it.
Three failure modes shaped the final code. First, a stuck bus: if the sensor held SDA low after a reset mid-transaction, the controller saw BUSY forever. I added a recovery routine that bit-bangs 9 SCL clocks with SDA released, then issues a STOP, and I ran it when read_regs timed out twice in a row. Second, clock stretching: the IMU stretched SCL during conversion, which is legal on I2C but breaks naive polling loops that assume a fixed clock period. I used the kernel timeout instead of counting clocks in userspace. Third, silent data corruption: I2C has ACK per byte but no CRC, so a flipped bit in a data byte still ACKs. I added a plausibility check, rejecting samples outside plus or minus 4 g for that rig and counting rejects in a counter the test operator could see. Over an 8-hour run we logged 11 rejects out of 5.7 million samples, all during motor start transients.
Validation was a known-input test, not just a live plot. I mounted the board on a tilt fixture, set it to 0, 30 and 90 degrees, and checked that X read 1.00, 0.87 and 0.00 g within 0.02 g. I also logged bus traffic with the analyser during a full run to confirm the 200 Hz target held with under 1 ms jitter, which the logger needed to align vibration peaks with the RPM encoder.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24What strategies do you use to ensure system scalability when adding new features or sensors?
Reported in Scalability for New Features and Sensors
The 90-second answer
I split the problem in two, because the scaling rules are opposite. On the aircraft, resources are fixed and behaviour must stay deterministic, so a new sensor has to fit a measured budget for CPU, bus bandwidth and memory before it ships. On the ground, resources can grow, so the design goal is to add a sensor type or a feature without rewriting ingestion, storage or the alerting path.
For the ground side I start from a capacity model, not from a diagram. Take a worked example: 200 aircraft, 20 sensors each, 10 Hz, 256 bytes per reading. That is 200 x 20 x 10 x 256 = 10.24 MB/s sustained, about 884 GB per day before replication. Double the sensor count and you double that figure, so I size the log partitions, the stream processors and the object store for at least 3x the current rate and I load test at that rate before the new sensor goes live. If the numbers do not fit, the feature does not ship.
Three mechanisms make that model usable in practice. First, ingestion is decoupled from processing through a partitioned log, partitioned by a hash of sensor identity so one aircraft cannot flood a single partition. Second, every sensor sits behind a versioned interface, so a new type registers a schema and a decoder instead of changing the core pipeline. Third, new features run behind a flag in shadow mode, consuming the same stream but writing to a separate output, until their latency and error rate match the existing path.
# Python 3.11, ground ingestion service
from dataclasses import dataclass
@dataclass(frozen=True)
class SensorReading:
sensor_id: str
schema_version: int
ts_ms: int
payload: bytes
def partition_key(reading: SensorReading) -> str:
# Hash on sensor_id, not aircraft_id: one chatty aircraft
# cannot create a hot partition.
return str(hash(reading.sensor_id) % 64)
def decode(reading: SensorReading) -> dict:
if reading.schema_version == 1:
return {"value": int.from_bytes(reading.payload, "big")}
if reading.schema_version == 2:
return {"value": int.from_bytes(reading.payload[:4], "big"),
"quality": reading.payload[4]}
raise ValueError(f"unknown schema {reading.schema_version}")The version check matters. A sensor firmware update that changes a payload layout should fail loudly at decode time for one partition, not silently corrupt aggregates downstream.
| Change | What breaks first | Mitigation I would name in the interview |
|---|---|---|
| New sensor type at same rate | Schema drift, decoder coupling | Versioned schema registry, contract tests per version |
| Same sensors, 10x fleet | Hot partition, broker disk | Partition by sensor hash, autoscale consumers, retention tiering |
| New feature on existing stream | Alert latency, duplicate side effects | Shadow mode, idempotent writes keyed by sensor_id and ts_ms |
| Sensor burst or clock skew | Unbounded queue, out-of-order aggregates | Bounded queue with explicit drop policy for non-critical telemetry, watermark on event time |
Failure modes I would call out without being asked: a partition keyed by aircraft_id creates a hot partition when one aircraft reports at 100 Hz; a queue with no drop policy turns a sensor fault into memory pressure on the gateway; and event-time aggregates without a watermark produce wrong rollups when a sensor clock drifts by seconds. Detection is concrete in each case: per-partition lag, gateway queue depth, and late-event rate on a dashboard, with an alert before the processor falls behind.
On the aircraft side the same discipline applies with hard limits. I would ask for the sensor's worst-case message rate on the bus, its processing time per frame, and its memory footprint, then check the sum against the partition budget with margin. If it does not fit, the answer is to decimate the rate or move processing to the ground, not to hope the bus absorbs it. That boundary, measured on the aircraft and elastic on the ground, is what lets a new feature or sensor arrive without a redesign.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25How do you architect software to be modular enough for long-term maintenance and system upgrades?
Reported in Modular Architecture for Upgrades
The 90-second answer
I would design around change points I can name on day one, not around a generic call for loose coupling. For a Leonardo system that may fly for 20 to 30 years, the predictable changes are hardware obsolescence, a new sensor or radio, a revised mission mode, and a certification baseline that cannot be rebuilt from scratch. So I separate the domain logic that encodes mission rules from everything that touches hardware, files, networks or a vendor SDK, and I make the seam between them a versioned contract.
In practice that means a hexagonal layout. The core knows nothing about a specific processor board, operating system or bus. It talks to ports, which are interfaces it owns. Adapters implement those ports for a particular platform. Swapping a board then means writing one adapter and re-running the hardware-in-the-loop tests for that adapter, not re-verifying the mission logic.
// Checked against Java 17. The core depends only on this port.
public interface SensorPort {
SensorSample read() throws SensorFault;
void configure(SensorConfig config) throws SensorFault;
}
public final class TrackerCore {
private final SensorPort sensor; // injected, never constructed here
public TrackerCore(SensorPort sensor) {
this.sensor = sensor;
}
public Track update() throws SensorFault {
SensorSample sample = sensor.read();
return fuse(sample); // mission logic, testable with a fake SensorPort
}
}The same rule applies inside the core. I split it into small modules with one reason to change each, for example track fusion, mission mode management and recording, and I forbid circular dependencies between them. An architecture test in CI fails the build if a module imports another module's internals instead of its public API. That test is cheap insurance. Without it, teams drift back to a monolith within two release cycles.
What the boundaries buy you, concretely
| Boundary | What it hides | Upgrade it enables |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Port interface | Register layout, timing, vendor SDK | Replace a sensor or board without touching fusion logic |
| Module API | Internal data structures of a module | Rewrite recording format while keeping the same read contract |
| Versioned data schema | On-disk and on-wire layout | Read old recordings after an upgrade, with a tested migration path |
| Build and deployment unit | Link-time and load-time coupling | Certify and ship one changed module instead of the whole baseline |
Versioning matters as much as the split. Every port and every persisted record carries a version. When I change a schema, I add a field, keep the old reader for one support window, and ship a migration that runs on load and is tested against golden files from the previous release. A worked example: a track record grows from 48 bytes to 56 bytes when a confidence field is added. The reader accepts both lengths, fills confidence with a documented default for old records, and the writer always emits the new length. If that migration is missing, the first upgrade in the field corrupts the archive and the failure shows up months later, during incident review, when nobody can replay the data.
Failure modes I watch for
The common one is a leaky port. The interface starts exposing vendor error codes, raw frames or timing assumptions, and the core quietly depends on them. The symptom is that a driver swap compiles but changes behaviour under load. I catch it by keeping vendor types out of the core package and by running the core test suite against two independent fake implementations of each port. If a test passes with one fake and fails with the other, the core was depending on an accident of the first implementation.
The second failure mode is a shared database or shared mutable state between modules. That turns a modular diagram into a distributed monolith, where every upgrade must be deployed everywhere at once. I avoid it by giving each module its own store and exchanging immutable events or explicit requests through the module API.
The third is over-modularisation. Splitting every class into its own deployable unit adds interface churn and makes a simple change touch five contracts. My rule of thumb is to split where change is expected and where a team or a certification boundary already exists, and to keep a module cohesive enough that most changes land in one place. If a change routinely touches three modules, the boundary is in the wrong place and I move it.
For a regulated programme I would also keep the evidence modular. Each module has its own unit tests, its own interface control document, and a stated dependency list, so an upgrade can be assessed for impact by walking that list instead of re-arguing the whole architecture. That is what makes long-term maintenance affordable: the cost of a change stays proportional to the module that changed, not to the size of the system.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: