Real Interview Questions for the Software Engineer at Thales
NewInterview Q&A
Q&A-1Walk through a personal project and explain its hardest problem?
Reported in Thales Software Engineer Interview Guide 2026: Process & Questions
The 90-second answer
My personal project is a flight recorder for a model glider. A Raspberry Pi on the glider sends GPS, barometer and IMU samples at 20 Hz over UDP to a Go service on a laptop. The service writes them to SQLite and serves a replay page that reconstructs altitude and ground track after the flight.
The hardest problem was not parsing the packets. It was that UDP reorders and duplicates them, and the Pi clock drifts against the laptop clock by up to 40 ms over a 90 minute flight. If I trusted arrival order or wall-clock time, the replay showed altitude spikes that never happened and the same sample twice.
I fixed it by making the Pi sequence number the ordering key, keeping device time only for display, and holding packets in a small reorder buffer before committing them.
How it works
Each packet carries seq (uint32, increments per sample), device_ms, and the sensor payload. The Go service keeps a window keyed by seq. A packet is committed only when every earlier seq has arrived or the gap has been declared lost after 250 ms. Duplicates are dropped by checking the committed high-water mark.
// Go 1.22, reorder buffer core
type Buffer struct {
next uint32 // next seq expected
pending map[uint32]Packet
lost int
}
func (b *Buffer) Add(p Packet) []Packet {
if p.Seq < b.next {
return nil // duplicate or late, already committed or dropped
}
b.pending[p.Seq] = p
var out []Packet
for {
pkt, ok := b.pending[b.next]
if !ok {
break
}
out = append(out, pkt)
delete(b.pending, b.next)
b.next++
}
return out
}The 250 ms timeout is handled by a ticker that calls DeclareLost() for a missing seq, increments lost, and advances next. That keeps replay moving during a burst of loss instead of stalling the whole flight.
Worked trace
Packets arrive out of order after a Wi-Fi hiccup. Buffer starts at next = 100.
| Arrival | seq | Action | Committed |
|---|---|---|---|
| 1 | 102 | held in pending | none |
| 2 | 101 | held in pending | none |
| 3 | 100 | commits 100, 101, 102 | 100, 101, 102 |
| 4 | 102 (retry) | seq < next, dropped | none |
| 5 | 104 | held, 103 missing | none |
| 6 | ticker fires | 103 declared lost, commits 104 | 104 |
Why those numbers
At 20 Hz, 250 ms covers 5 samples. In my tests with tc netem adding 80 ms jitter and 5% loss, a 250 ms window recovered 99.2% of samples in order. A 50 ms window recovered only 91%, because jitter bursts exceeded it. A 1 s window recovered 99.8% but added a visible 1 s lag to live replay, which made the glider feel unresponsive on the ground station. 250 ms was the point where lag stopped mattering and loss recovery was already close to the ceiling.
Storage was never the constraint. 20 samples/s x 180 bytes x 3600 s is about 13 MB per hour before SQLite overhead, so I could keep the raw packet log on disk and rebuild the database from it.
Failure modes I tested for
A Pi reboot mid-flight resets seq to 0. I added a session_id generated at boot and stored in every packet, so the buffer resets cleanly instead of treating new samples as duplicates of the old session. A second failure was a stuck sensor repeating the last value. The replay page now flags a run of identical altitude values longer than 2 s as stale, rather than drawing a flat line that looks like level flight.
For testing, I recorded raw UDP traffic with tcpdump and replayed it through the service in a Go test. I could drop, duplicate or reorder packets deterministically and assert the committed sequence. That replay harness is what I would reuse in a team codebase, because it turns a timing bug that happens once in the field into a test that runs on every commit.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Solve Two Sum two ways and discuss the complexity trade-offs?
Reported in Thales Software Engineer Interview Guide 2026: Process & Questions
The 90-second answer
Given nums = [2, 7, 11, 15] and target = 9, return indices [0, 1]. I would show the brute force first because it is obviously correct, then the hash map version I would actually ship.
Brute force checks every pair. Hash map remembers each value seen so far and looks up the complement target - nums[i] in one step. That trades memory for time: O(n^2) time and O(1) extra space against O(n) time and O(n) extra space.
Way 1: brute force
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []Way 2: one pass with a hash map
def two_sum_hash(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
complement = target - x
if complement in seen:
return [seen[complement], i]
seen[x] = i
return []Trace for nums = [2, 7, 11, 15], target = 9:
| i | x | complement | seen before step | action |
|---|---|---|---|---|
| 0 | 2 | 7 | {} | store 2 -> 0 |
| 1 | 7 | 2 | {2: 0} | hit, return [0, 1] |
The early return matters. On a hit at i = 1 the hash version stops after 2 steps. Brute force also stops early on this input, but its worst case is still quadratic.
Complexity, with real figures
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Brute force | O(n^2) | O(1) | n = 100,000 means up to ~5e9 pair checks in the worst case, too slow for an interactive request |
| Hash map | O(n) average | O(n) | n = 100,000 means 100,000 inserts and lookups, plus a dict of up to 100,000 entries |
| Sorted + two pointers | O(n log n) | O(n) if you keep original indices, O(1) if you may reorder | Only works if returning values is acceptable, or you sort pairs of (value, index) |
Hash map time is average case. A pathological hash collision pattern can degrade lookups, and in a language with a hash map that an attacker can influence, that is a denial of service concern. In practice for an interview answer I state the average case assumption and move on. If worst case guarantees matter, say so explicitly.
Edge cases I would name before coding
Duplicates: nums = [3, 3], target = 6. The hash version stores the first 3 at index 0, then at i = 1 the complement 3 is found and returns [0, 1]. It never matches an element with itself because the lookup happens before the insert for the current element. Reversing those two lines is the classic bug.
No solution: both versions return [] after a full scan. I would confirm with the interviewer whether the contract guarantees exactly one solution, as LeetCode does, or whether no solution is a real case to handle.
Negative numbers and large values: no special handling needed in Python. In C++ or Java I would check for overflow in target - x when values sit near INT_MAX, and use a wider type or a checked subtraction.
When I would not use the hash map
If memory is the hard constraint, for example a fixed buffer on an embedded target where allocating a map for a large input is not allowed, brute force or the sorted approach may be the only option. If the input arrives sorted and indices are not required, two pointers give O(n) time and O(1) space with no hash table at all. If the array is sorted but indices are required, sorting (value, index) pairs costs O(n log n) time and O(n) space, which is worse than the hash map on both counts, so I would only pick it when a hash map is unavailable.
That framing is what I would close with: state the assumption of one solution, show the quadratic baseline, then the linear hash version, and name the memory cost as the price paid.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Solve a problem using two-pointer techniques?
Reported in Thales Software Engineer Interview Guide 2026: Process & Questions
The 90-second answer
I would solve this concrete version: given a sorted array of integers and a target, return two distinct indices whose values sum to the target, or report that no pair exists. The sorted order is the assumption that makes two pointers work, so I would state it first and check it in tests.
# Python 3.12
def pair_sum(sorted_nums: list[int], target: int) -> tuple[int, int] | None:
left, right = 0, len(sorted_nums) - 1
while left < right:
total = sorted_nums[left] + sorted_nums[right]
if total == target:
return (left, right)
if total < target:
left += 1 # sum too small, discard the smallest value
else:
right -= 1 # sum too large, discard the largest value
return NoneEach step discards one endpoint, so the loop runs at most n - 1 iterations. Time is O(n) and extra space is O(1). That constant space matters on memory constrained embedded targets, where a hash map for the unsorted variant would allocate n entries.
Worked trace
For [-1, 0, 2, 4, 7, 9] and target 11:
| Step | left | right | sorted_nums[left] + sorted_nums[right] | Move |
|---|---|---|---|---|
| 1 | 0 (-1) | 5 (9) | 8 | left += 1 |
| 2 | 1 (0) | 5 (9) | 9 | left += 1 |
| 3 | 2 (2) | 5 (9) | 11 | return (2, 5) |
Why discarding is safe
If the current sum is below target, sorted_nums[left] cannot pair with any value at or left of right, because every remaining candidate is at most sorted_nums[right]. The symmetric argument holds when the sum is above target. That monotonicity is the whole proof, and it collapses the moment the input is unsorted.
The other common shape
Two pointers also run in the same direction, with a fast pointer scanning ahead of a slow pointer. That covers in-place removal, cycle detection, and linked list midpoint problems.
| Shape | Pointers | Typical use | Extra space |
|---|---|---|---|
| Opposite ends | left at start, right at end, moving inward | Pair sum, palindrome check, container with most water | O(1) |
| Same direction | slow and fast both start at the beginning, fast ahead | Remove duplicates in place, find midpoint, detect a cycle | O(1) |
Failure modes I would test for
Unsorted input is the main one. The function above would return a wrong answer or None without any error, so callers either sort first at O(n log n) cost or switch to a hash map at O(n) time and O(n) space. I would add a sortedness assertion in debug builds rather than paying for a full scan in production if the caller guarantees order.
Duplicates need care in variants that count pairs. With [1, 1, 1, 1] and target 2, the basic version returns (0, 3) correctly, but a counting version that increments both pointers on a match must skip duplicate values or it will overcount. The loop condition left < right also prevents pairing an element with itself, which matters for inputs such as [3] with target 6.
In fixed width languages, sorted_nums[left] + sorted_nums[right] can overflow before the comparison. Python integers do not overflow, but in C or Java I would compare using a wider type or compare sorted_nums[right] against target - sorted_nums[left] with the subtraction checked for overflow. A quick property test over random sorted arrays against a brute force O(n squared) reference catches all three issues before review.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Solve a problem using dynamic programming?
Reported in Thales Software Engineer Interview Guide 2026: Process & Questions
The 90-second answer
I would state the problem before coding it. Take the version I get most often in interviews: given coin denominations and a target amount, return the fewest coins that make the amount, or -1 if it is impossible. I would assume unlimited coins, positive denominations, and a non-negative target. Then I define the state, write the recurrence, fill it bottom-up, and reconstruct the answer.
Let amount = A and coins = [1, 5, 10, 25] for a worked example. Let dp[x] be the fewest coins for amount x. The recurrence is:
dp[0] = 0, and for x > 0, dp[x] = 1 + min(dp[x - c]) over every coin c <= x.
That is optimal substructure plus overlapping subproblems. A greedy choice fails here in general, for example coins [1, 3, 4] for amount 6: greedy takes 4 + 1 + 1 (3 coins), DP finds 3 + 3 (2 coins). I would say that counterexample out loud, because it shows why the recurrence is needed rather than sorting coins descending.
Worked trace
For coins [1, 3, 4] and A = 6:
| x | dp[x] | chosen last coin | why |
|---|---|---|---|
| 0 | 0 | none | base case |
| 1 | 1 | 1 | dp[0] + 1 |
| 2 | 2 | 1 | dp[1] + 1 |
| 3 | 1 | 3 | dp[0] + 1 |
| 4 | 1 | 4 | dp[0] + 1 |
| 5 | 2 | 1 or 4 | dp[4] + 1 or dp[1] + 1 |
| 6 | 2 | 3 | dp[3] + 1 |
Reconstruction walks back from dp[6]: last coin 3, remainder 3, last coin 3, remainder 0. Result: [3, 3].
Code I would write live
Python 3.12, iterative version. I prefer this in an interview over recursion because the call stack and memo dictionary are explicit, and the fill order is visible to the interviewer.
def min_coins(coins: list[int], amount: int) -> list[int] | None:
INF = amount + 1 # any real answer uses at most `amount` coins of value 1
dp = [INF] * (amount + 1)
choice = [-1] * (amount + 1)
dp[0] = 0
for x in range(1, amount + 1):
for c in coins:
if c <= x and dp[x - c] + 1 < dp[x]:
dp[x] = dp[x - c] + 1
choice[x] = c
if dp[amount] == INF:
return None
result = []
x = amount
while x > 0:
c = choice[x]
result.append(c)
x -= c
return resultTime is O(A * k) for k denominations, space is O(A) for dp plus O(A) for choice. With A = 10,000 and k = 4 that is 40,000 transitions, trivial. With A = 10^9 it is not, and I would flag that DP is pseudo-polynomial in the amount, not in the input size.
Trade-offs and failure modes I would name
| Approach | When it wins | Where it breaks |
|---|---|---|
| Top-down with memo | State space is sparse, only reachable states computed | Recursion depth, repeated states if memo key is wrong |
| Bottom-up table | Deterministic order, easy to bound memory and time | Computes unreachable states, large A exhausts memory |
| Greedy | Canonical coin systems, O(k log k) | Counterexamples such as [1, 3, 4] above |
Three concrete failures to check before calling it done. First, unreachable amounts: if no coin is 1, dp[amount] stays at INF and the code must return None, not a partial list. Second, reconstruction: storing only dp gives the count but not the coins, so choice (or a parent pointer) is required, and a bug there produces a list whose sum does not equal A. I would assert sum(result) == amount in a test. Third, scale: on a constrained embedded target, which is the context I think about at Thales, an O(A) table with A derived from a sensor range can blow a fixed memory budget or make worst-case execution time unpredictable. Then I would ask whether the state can be compressed to two rows, whether the amount range can be capped, or whether the problem is actually a shortest-path problem better solved with Dijkstra on the remainder graph.
If the interviewer changes the problem to 0/1 knapsack or edit distance, the same skeleton holds: name the state in one sentence, write the recurrence from the last decision, state the base case, then fill in an order that respects dependencies. The interviewer is usually testing whether I can do that without jumping straight to code.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Write a complex SQL query using INNER/LEFT JOINs, GROUP BY, aggregates and window functions like DENSE_RANK()?
Reported in Thales Software Engineer Interview Guide 2026: Process & Questions
The 90-second answer
I would state the schema first, then build the query in layers: join, aggregate, rank. That order matters because window functions run after GROUP BY, so DENSE_RANK() can only rank the aggregated rows, not the raw readings.
Assume PostgreSQL 16 and this schema:
sites(site_id INT PRIMARY KEY, name TEXT);
assets(asset_id INT PRIMARY KEY, site_id INT REFERENCES sites, asset_type TEXT);
readings(asset_id INT REFERENCES assets, recorded_at TIMESTAMPTZ, value_c NUMERIC);Task: for each site, rank asset types by average temperature over the last 30 days, including asset types with no readings in that window.
WITH agg AS (
SELECT
s.site_id,
s.name AS site_name,
a.asset_type,
COUNT(r.asset_id) AS reading_count,
AVG(r.value_c) AS avg_temp_c,
MAX(r.value_c) AS max_temp_c
FROM sites s
JOIN assets a ON a.site_id = s.site_id
LEFT JOIN readings r
ON r.asset_id = a.asset_id
AND r.recorded_at >= now() - INTERVAL '30 days'
GROUP BY s.site_id, s.name, a.asset_type
),
ranked AS (
SELECT
*,
DENSE_RANK() OVER (
PARTITION BY site_id
ORDER BY avg_temp_c DESC NULLS LAST
) AS temp_rank
FROM agg
)
SELECT * FROM ranked WHERE temp_rank <= 2;Why each piece is there. JOIN assets is INNER: a site with no assets has nothing to report. LEFT JOIN readings keeps those assets and returns NULL for value_c when no reading matches. That is why the count is COUNT(r.asset_id), not COUNT(*). COUNT(*) would count the null-extended row as 1 and claim an asset with no readings had one reading. AVG and MAX ignore NULL inputs, so an asset with no readings gets NULL for both, which is correct. Putting the date predicate in the ON clause, rather than in WHERE, is what preserves the left join. In WHERE it would discard every null-extended row and silently turn the query back into an inner join.
GROUP BY collapses readings to one row per site and asset type. The window function then partitions those rows by site and orders them by average temperature. DENSE_RANK() gives tied rows the same rank and does not skip the next rank: averages of 80, 80, 75 produce ranks 1, 1, 2. RANK() would produce 1, 1, 3. ROW_NUMBER() would break the tie arbitrarily and produce 1, 2, 3. If the interviewer wants every asset tied at the top, DENSE_RANK() is the right choice. If they want exactly one winner per site, ROW_NUMBER() with a deterministic tiebreaker such as asset_type is the right choice.
Worked trace. Hypothetical data for one site, after aggregation:
| asset_type | reading_count | avg_temp_c | max_temp_c | temp_rank |
|---|---|---|---|---|
| pump | 120 | 81.2 | 94.0 | 1 |
| valve | 98 | 81.2 | 90.5 | 1 |
| motor | 140 | 74.6 | 88.1 | 2 |
| sensor | 0 | NULL | NULL | 3 |
The outer WHERE temp_rank <= 2 returns pump, valve and motor. It cannot go in the same SELECT as the window function, because WHERE is evaluated before window functions. Filtering on a window result needs the CTE or a subquery, as written here.
Failure modes I would name unprompted. The big one is join fan-out. If I joined readings to a second one-to-many table, such as maintenance events, in the same query, each reading would be duplicated once per event and SUM and AVG would inflate. The fix is to pre-aggregate each one-to-many side in its own CTE and join the aggregates. A second trap is grouping by a non-unique column. Grouping by site_name instead of site_id merges two sites that happen to share a name. A third is performance: this query needs an index on readings(asset_id, recorded_at) or the left join scans the whole readings table per asset. With 10 million readings and no index, the aggregation is the slow part, not the ranking.
If the interviewer changes the ask to "top asset per site", I would swap DENSE_RANK() for ROW_NUMBER() and add the tiebreaker. If they ask for a running total instead, I would use SUM(avg_temp_c) OVER (PARTITION BY site_id ORDER BY avg_temp_c DESC ROWS UNBOUNDED PRECEDING). The structure stays the same: aggregate first, window second, filter last.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6How would you optimize an inefficient SQL query by adding appropriate indexes?
Reported in Thales Software Engineer Interview Guide 2026: Process & Questions
The 90-second answer
I would not start by creating an index. I would reproduce the query, run EXPLAIN (ANALYZE, BUFFERS) on production-like data, and find where time actually goes: a sequential scan, a sort, or rows discarded by a filter. Then I would add the smallest index that turns that operation into a bounded lookup, and re-run the same plan to prove it helped. If the query is WHERE customer_id = ? AND created_at >= ? ORDER BY created_at DESC, the candidate is a composite B-tree on (customer_id, created_at DESC). Equality column first, range and sort column second. That one index serves the filter and the ordering.
Assume a PostgreSQL 16 table of maintenance events, 2 million rows, and this query from a dashboard:
-- checked against PostgreSQL 16
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, device_id, severity, created_at
FROM maintenance_events
WHERE device_id = 42
AND severity = 'critical'
AND created_at >= now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 100;Before the index, a typical plan (hypothetical figures, labelled as such) looks like:
| Node | Rows | Time | What it tells you |
|---|---|---|---|
| Sort | 18,400 | 210 ms | Sorting every match |
| Seq Scan | 18,400 of 2,000,000 | 240 ms | Reading the whole table, discarding 99% |
| Planning + execution | ~450 ms | Dashboard timeout risk at peak |
The fix:
CREATE INDEX CONCURRENTLY idx_events_device_sev_time
ON maintenance_events (device_id, severity, created_at DESC)
INCLUDE (id);CONCURRENTLY matters on a live system. A plain CREATE INDEX takes a lock that blocks writes, which on a Thales telemetry or maintenance gateway with a tight ingest budget is not acceptable during the day. After the index, the same query should show an index scan returning at most 100 rows, with buffers dropping from tens of thousands to a few hundred. If it does not, the index is decoration and I would remove it.
Why this shape, and when it fails
| Index choice | Use it when | Cost |
|---|---|---|
| Single column B-tree | One selective equality filter | Cheap, but useless for multi-column filters |
| Composite B-tree | Equality plus range or sort, as above | Larger, slower writes |
Covering (INCLUDE) | Query needs only indexed columns | Avoids heap fetches, widest index |
Partial (WHERE severity = 'critical') | Rare subset queried often | Small, but only helps that exact predicate |
Three failure modes I check before declaring victory. First, the planner ignores the index: a function on the column (WHERE date(created_at) = ...), a leading wildcard (LIKE '%crit%'), or implicit type casts all prevent a B-tree lookup. The fix is to rewrite the predicate or add an expression index, not a second B-tree. Second, selectivity is too low. If severity = 'critical' matches 40% of rows, the planner will correctly choose a sequential scan, and forcing an index makes it slower. Third, write amplification. Every index is maintained on insert and update. On a write-heavy ingest path, three indexes can turn a 5 ms insert into 15 ms and grow storage by 30 to 50%. I would measure insert p99 before and after, and drop indexes that no query uses, checked via pg_stat_user_indexes.
Finally I would verify with the same EXPLAIN ANALYZE on the same data volume, check that the dashboard query stays under its latency budget at peak concurrency, and confirm no regression on the write path. An index that helps one read and breaks ingest is not an optimisation.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Explain normalization, indexing strategies and ACID properties in a real-world database scenario?
Reported in Thales Software Engineer Interview Guide 2026: Process & Questions
The 90-second answer
Take a maintenance system for a fleet of aircraft. Technicians log jobs against an airframe, a part, and a work order. If I dump that into one wide table, updates corrupt history. If I split it too far, every job lookup becomes a six-way join on a system that must answer in under 200 ms during a turnaround. Normalization decides where the truth lives, indexes decide how fast we find it, and ACID decides what happens when the power fails halfway through issuing a part.
Normalization, with a concrete schema
Start unnormalized: one row per job repeats the airframe model, technician name, and part description. Change a technician's name and you update 4,000 rows. Miss one and reports disagree.
Normalized to 3NF:
-- PostgreSQL 16
CREATE TABLE airframes (
airframe_id TEXT PRIMARY KEY,
model TEXT NOT NULL,
serial_no TEXT NOT NULL UNIQUE
);
CREATE TABLE technicians (
technician_id TEXT PRIMARY KEY,
full_name TEXT NOT NULL,
certification TEXT NOT NULL
);
CREATE TABLE parts (
part_id TEXT PRIMARY KEY,
description TEXT NOT NULL,
unit_cost_gbp NUMERIC(10,2) NOT NULL
);
CREATE TABLE jobs (
job_id TEXT PRIMARY KEY,
airframe_id TEXT NOT NULL REFERENCES airframes,
technician_id TEXT NOT NULL REFERENCES technicians,
part_id TEXT NOT NULL REFERENCES parts,
started_at TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL CHECK (status IN ('open','closed','cancelled'))
);1NF removes repeating groups. 2NF removes partial dependency: technician name depends on technician_id, not on job_id, so it moves out. 3NF removes transitive dependency: part description depends on part_id, not on the job. The win is single-point update. The cost is joins, which is why I stop at 3NF here and denormalize only measured hot paths, for example a jobs_open_count maintained by a trigger if the dashboard query runs 50 times a minute.
Indexing strategies
The two queries that matter: jobs for one airframe in a date range, and open jobs by technician.
CREATE INDEX jobs_airframe_started_idx
ON jobs (airframe_id, started_at DESC);
CREATE INDEX jobs_open_technician_idx
ON jobs (technician_id) WHERE status = 'open';| Index type | Use here | Trade-off |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| B-tree composite | (airframe_id, started_at) | Serves equality plus range in one scan |
| Partial B-tree | open jobs only | Small, fast, but useless once a job closes |
| Covering index | INCLUDE (part_id, status) | Index-only scan, wider index, more write cost |
| Unique | serial_no | Enforces the constraint, catches duplicate airframes |
Worked trace, hypothetical figures labelled as such: 2 million job rows. Without an index, WHERE airframe_id = 'A320-214' scans 2 million rows, about 900 ms in our test. With the composite index it touches roughly 300 matching entries, about 4 ms. The price: every insert into jobs now updates two indexes, so write throughput drops from about 8,000 to 6,500 inserts per second on the same hardware. I accept that because reads dominate, 20 to 1. I would drop the partial index first if writes became the bottleneck, since it only helps one query.
ACID in the issuing transaction
Issuing a part must do three things together: decrement stock, mark the job, write an audit row. In PostgreSQL:
BEGIN;
UPDATE inventory SET qty = qty - 1
WHERE part_id = 'P-8841' AND qty > 0;
-- check rowcount = 1, else ROLLBACK
UPDATE jobs SET status = 'closed' WHERE job_id = 'J-10293';
INSERT INTO audit_log (job_id, actor, action) VALUES ('J-10293','tech-77','part_issued');
COMMIT;Atomicity: if the process dies after the first update, rollback leaves stock unchanged. No half-issued part. Consistency: the qty > 0 guard plus a CHECK (qty >= 0) constraint mean the database refuses negative stock even if application code has a bug. Isolation: at the default READ COMMITTED, two technicians issuing the last unit concurrently can both read qty = 1. The UPDATE ... WHERE qty > 0 serializes them on the row lock, so the second blocks, then sees qty = 0 and updates zero rows. I would only move to SERIALIZABLE if a multi-row invariant, such as total issued never exceeding total delivered, could not be expressed as a constraint. Durability: COMMIT returns only after the WAL record is flushed to disk with synchronous_commit = on. A crash after that point replays the log on restart and the issue survives.
Failure modes I would name in the loop: over-normalization that turns a 5 ms lookup into a 120 ms join chain, an index on a low-cardinality column like status alone that the planner ignores, and assuming ACID protects against application bugs. It does not. It guarantees the transaction you wrote executes atomically, so the transaction itself has to encode the business rule.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Write a pyramid program using a char array in C?
Reported in Thales Software Engineer interview experience (May 2026)
The 90-second answer
I would clarify two things first: the height, and whether the pyramid is just printed or stored in the array. Assuming height n = 5, character '*', centred, and printed to stdout, I would build each row in a char array and print it. That shows I can handle the loops, the null terminator, and the buffer size, which is usually what the follow-up probes.
// C17, checked with gcc -std=c17 -Wall -Wextra
#include <stdio.h>
int main(void)
{
const int n = 5;
const char ch = '*';
char row[64]; /* 2*n - 1 chars + '\0' must fit */
if (n <= 0 || 2 * n > (int)sizeof(row)) {
fprintf(stderr, "height out of range\n");
return 1;
}
for (int i = 1; i <= n; i++) {
int pos = 0;
for (int s = 0; s < n - i; s++) row[pos++] = ' ';
for (int k = 0; k < 2 * i - 1; k++) row[pos++] = ch;
row[pos] = '\0';
printf("%s\n", row);
}
return 0;
}Output for n = 5:
*
***
*****
*******
*********Why build the row in an array first
Printing spaces and stars directly with nested printf calls works, but it hides the row as a value. Building row first makes the length explicit: n - i spaces, then 2*i - 1 copies of ch, then '\0'. If the interviewer then asks to store the whole pyramid, the same row logic fills a 2D array, char pyr[n][2*n], one row per line, each null terminated. If they ask for a single flat array, the index is i * (2*n) + j, and the newline is just another character in that buffer.
Worked trace for n = 4, so the buffer check is 2*4 = 8 <= 64:
i | spaces n-i | stars 2*i-1 | pos before '\0' | row printed |
|---|---|---|---|---|
| 1 | 3 | 1 | 4 | * |
| 2 | 2 | 3 | 5 | *** |
| 3 | 1 | 5 | 6 | ***** |
| 4 | 0 | 7 | 7 | ******* |
Failure modes I would name unprompted
Forgetting the terminator is the classic one. row[pos] = '\0' is not optional, and printf("%s", row) without it reads past the end of the array until it happens to find a zero byte. The second is sizing. The longest row needs 2*n - 1 characters plus the terminator, so a fixed char row[64] silently overflows for n >= 33. The guard at the top turns that into a clean error instead of stack corruption. The third is input. If n comes from scanf, I check the return value and reject n <= 0; a negative height makes the space loop run zero times and the star loop run with a negative bound, which in unsigned arithmetic would be catastrophic.
Alternatives and when I would switch
If the pyramid is large or needs to be reused, I would allocate char *row = malloc(2*n) and free it, or use a VLA char row[2*n] in C99 and later, accepting that a huge n can still exhaust the stack. If the output goes to a file or a network buffer, I would write into that destination directly and skip the intermediate row, because the array then only adds a copy. For a quick whiteboard answer, direct printing is faster to write, but I would still state the row length out loud, since that is where off-by-one errors show up in review.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Remove duplicates from an array and print the result?
Reported in Thales Software Engineer interview experience (May 2026)
The 90-second answer
Assume an unsorted int array, duplicates defined by equality, and the original order of first occurrences preserved. I would write the in-place version first because it needs no extra allocation and is easy to defend in C:
#include <stdio.h>
int main(void) {
int a[] = {4, 2, 4, 7, 2, 9};
int n = 6;
int m = 0; /* length of the deduplicated prefix */
for (int i = 0; i < n; i++) {
int seen = 0;
for (int j = 0; j < m; j++) {
if (a[j] == a[i]) { seen = 1; break; }
}
if (!seen) a[m++] = a[i];
}
for (int i = 0; i < m; i++) {
printf("%d%c", a[i], i + 1 == m ? '\n' : ' ');
}
return 0;
}Output: 4 2 7 9
The invariant is that a[0..m-1] always holds the distinct values seen so far, in first-occurrence order. Writing to a[m] is safe because m <= i, so the write never clobbers an element that has not been read yet. That is the point an interviewer usually probes: the code compacts in place without a second array.
Worked trace
i | a[i] | Found in a[0..m-1]? | Action | m after |
|---|---|---|---|---|
| 0 | 4 | no | copy to a[0] | 1 |
| 1 | 2 | no | copy to a[1] | 2 |
| 2 | 4 | yes, at index 0 | skip | 2 |
| 3 | 7 | no | copy to a[2] | 3 |
| 4 | 2 | yes, at index 1 | skip | 3 |
| 5 | 9 | no | copy to a[3] | 4 |
Choosing the method
The nested loop is O(n^2) time and O(1) extra space. That is the right default for small, fixed-size buffers, which is common in embedded and firmware code where malloc may be unavailable or undesirable. It stops being right when n grows.
| Method | Time | Extra space | Preserves order | Precondition |
|---|---|---|---|---|
| Nested scan, in place | O(n^2) | O(1) | yes | none |
| Sort, then two pointers | O(n log n) | O(1) to O(n) depending on sort | no | order may change |
| Hash set, then emit | O(n) average | O(n) | yes, if emitted in scan order | hashable elements |
For a sorted array the two-pointer version is cleaner: keep a write index m, advance the read index, and copy a[i] only when it differs from a[m-1]. That runs in O(n) with no hash table. For a large unsorted array, a hash set wins on time, but in C you now own the hash table, its resizing, and its worst case. At n = 10,000, the nested scan does roughly 50 million comparisons, while the hash version does about 10,000 insertions. At n = 50, the nested scan does about 1,225 comparisons and the hash table overhead is hard to justify.
Failure modes to name
Empty input: n = 0 must print nothing and not read a[0]. The loops above handle that because both bounds are checked against m and n. A single element returns itself. The classic bug is comparing against the whole original array instead of the compacted prefix, which reintroduces duplicates that were already skipped, or iterating j < i while also writing to a[m] in a way that overwrites unread data when the logic changes. Another is using a sentinel value such as 0 or -1 to mark removed slots. That breaks as soon as the input legitimately contains the sentinel, which is why the prefix-length approach is safer than marking.
If the interviewer changes the constraint mid-answer, I would state the switch explicitly: sorted input gets the linear two-pointer pass, large unsorted input gets a hash set, and small in-place input stays with the nested scan. That shows the trade-off is driven by size and memory, not by habit.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Which design patterns have you used before?
Reported in Thales Software Engineer interview experience (May 2026)
The 90-second answer
I use a small set well rather than naming twenty. In production code I have shipped Strategy, Factory, State, Observer, Adapter and Command, mostly in Java and C++ services handling telemetry, device control and configuration. The common thread is testability under constraints: each pattern replaces a conditional or a hidden dependency with an explicit, injectable collaborator that a unit test can swap without hardware.
A concrete example is a telemetry decoder. Message formats arrive from several sensors, each with its own framing and checksum rules. Instead of a switch statement growing in the parser, I define a Decoder strategy per format and a factory that selects it from the message header.
// Java 17, checked against the OpenJDK 17 API
public interface Decoder {
Reading decode(byte[] frame) throws DecodeException;
}
public final class DecoderFactory {
private final Map<Format, Decoder> decoders;
public DecoderFactory(Map<Format, Decoder> decoders) {
this.decoders = Map.copyOf(decoders);
}
public Decoder forFormat(Format format) throws DecodeException {
Decoder decoder = decoders.get(format);
if (decoder == null) {
throw new DecodeException("unsupported format: " + format);
}
return decoder;
}
}The factory fails loudly on an unknown format. A silent default decoder would turn a configuration error into plausible but wrong readings, which is the failure mode that matters in safety-related code. Adding a format means adding one class and one map entry, and the parser stays closed for modification.
| Pattern | Where I used it | What it buys | When I avoid it |
|---|---|---|---|
| Strategy | Sensor decoders, retry policies, compression codecs | Algorithms vary independently and are unit tested in isolation | Only one implementation will ever exist |
| Factory | Decoder and device driver creation from configuration | Construction rules live in one place, invalid combinations are rejected early | It becomes a god object that knows every class in the system |
| State | Device lifecycle: idle, configuring, active, fault | Illegal transitions are unrepresentable instead of checked in scattered if statements | The state count is small and a simple enum with a transition table reads better |
| Observer | Telemetry subscribers, audit logging | Producers do not know their consumers, subscribers can be added without touching the producer | Ordering or delivery guarantees are required but the bus does not provide them |
| Adapter | Legacy vendor SDK behind our own interface | Vendor types do not leak into domain code, the SDK can be replaced | The vendor interface already matches ours, then the adapter is pure indirection |
| Command | Configuration changes, operator actions | Actions become objects that can be logged, queued and undone | The action is a single direct method call with no queueing or audit need |
State deserves a diagram because it is where the pattern earns its keep. A device controller written as booleans (isActive, isFaulty, isConfiguring) allows combinations such as active and faulty at once. The state version makes each state a class that only accepts the transitions valid from it.
Failure modes I watch for
Observer is the one I treat most carefully. A subscriber that throws, or that blocks, can stall the publisher if delivery is synchronous. In one system I moved audit logging to a bounded queue with a drop counter and an alert at 80 percent full, rather than letting a slow disk writer back-pressure the control loop. The trace is simple: queue depth climbs from 12 to 400 in a minute, the counter increments, and the on-call sees the alert before readings are lost.
Singleton I avoid in application code. It hides a dependency, makes parallel tests interfere, and in a certified codebase it complicates the evidence that each component can be tested alone. I prefer constructor injection with the composition root wiring instances once at startup. That gives the same single instance where one is genuinely needed, without a global accessor.
Factory has a matching trap. If every new class needs a factory branch, the factory becomes the switch statement I was trying to remove. I keep factories keyed by an external identifier from configuration or a message header, so a new strategy registers itself rather than editing central code.
How I would defend the choice in review
For each pattern I can point to the test it enables. A strategy is tested with fake inputs and expected readings, no socket required. A state class is tested by attempting every transition and asserting the illegal ones throw. An adapter is tested against a fake vendor SDK. If a pattern does not make a test easier or remove a real conditional, I drop it. In regulated work that discipline also matters for traceability: every pattern in the design should map to a requirement or a concrete problem, not to a catalogue.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11How would you restructure the classes, design the constructors, and organize the implementation for a printing system that handles specific file types?
Reported in Thales Software Engineer interview experience (May 2026)
The 90-second answer
I would split the current god class into three responsibilities: describing what to print, converting a file into pages, and sending pages to a device. A PrintJob holds the immutable request. A DocumentRenderer per file type turns bytes into a common page model. A Printer only knows how to accept pages in that model and report device state. A small registry picks the renderer, so adding a format means adding one class and one registration line, and the spooler never learns about PDF or PCL internals.
Assume Java 17, a desktop or embedded service printing PDF, PostScript, PCL and raster images (PNG, TIFF) to local or network printers. The key constraints I would state up front: file type comes from content, not extension; conversion must not happen in a constructor; and a failed page must be reported, never silently skipped.
Restructuring the classes
The usual starting point is one PrinterService with if (type.equals("pdf")) ... else if (type.equals("png")) ... and a different constructor per caller. That couples parsing, layout and hardware, and every new format edits the same method. I would replace it with a strategy per format behind one interface, plus a registry keyed by detected content.
| Concern | Before | After |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Format handling | if chain in the service | DocumentRenderer implementations, one per format |
| Choosing a format | Caller passes an extension string | RendererRegistry sniffs magic bytes (%PDF, PNG signature, PCL escape) |
| Job data | Mutable fields set after construction | Immutable PrintJob value object |
| Device access | Service opens sockets directly | Printer depends on a DeviceConnection interface |
| Failure reporting | Returns null or prints to stdout | Throws typed exceptions, spooler records per-page status |
// Checked against Java 17. No I/O in any constructor below.
public interface DocumentRenderer {
boolean supports(byte[] header);
List<Page> render(byte[] fileBytes, PrintOptions options) throws RenderException;
}
public final class RendererRegistry {
private final Map<String, DocumentRenderer> byFormat;
public RendererRegistry(List<DocumentRenderer> renderers) {
this.byFormat = renderers.stream()
.collect(Collectors.toUnmodifiableMap(r -> r.formatId(), r -> r));
}
public DocumentRenderer forFile(byte[] bytes) throws UnsupportedFormatException {
return byFormat.values().stream()
.filter(r -> r.supports(bytes))
.findFirst()
.orElseThrow(() -> new UnsupportedFormatException("no renderer for file signature"));
}
}Constructor design
Constructors do two jobs only: store dependencies and check invariants. Anything that can fail because of the outside world (opening a device, reading a file, negotiating printer capabilities) moves to a factory method or an explicit open() call, so a half-built object never exists.
public final class PrintJob {
private final JobId id;
private final PrinterId printerId;
private final PrintOptions options;
public PrintJob(JobId id, PrinterId printerId, PrintOptions options) {
this.id = Objects.requireNonNull(id, "id");
this.printerId = Objects.requireNonNull(printerId, "printerId");
this.options = Objects.requireNonNull(options, "options");
if (options.copies() < 1 || options.copies() > 99) {
throw new IllegalArgumentException("copies out of range: " + options.copies());
}
}
// getters only, no setters
}
public final class Printer {
private final PrinterId id;
private final PrinterCapabilities capabilities;
private final DeviceConnection connection; // injected, already opened by factory
public Printer(PrinterId id, PrinterCapabilities capabilities, DeviceConnection connection) {
this.id = Objects.requireNonNull(id);
this.capabilities = Objects.requireNonNull(capabilities);
this.connection = Objects.requireNonNull(connection);
}
}PrintOptions is a record, so copies, colour mode and duplex are fixed at creation. A static factory PrintJob.fromRequest(...) handles parsing and validation that needs the raw request, keeping the constructor trivial to test. Dependencies arrive through the constructor, which makes the spooler testable with a fake DeviceConnection and no real printer.
Organising the implementation
I would use four packages, with dependencies pointing one way: api (request DTOs, validation), application (spooler, job lifecycle), domain (PrintJob, Page, capabilities, exceptions), and infrastructure (renderers, device drivers, registry wiring). Domain classes never import a PDF library. That matters in a Thales-style review because the safety and audit story stays readable: every job gets an ID, every page transition is logged, and an unsupported or corrupt file fails before any page reaches the device.
Worked trace for two inputs:
| Step | PDF input | PNG input |
|---|---|---|
| Sniff | %PDF header matches PdfRenderer | PNG signature matches RasterRenderer |
| Render | 12 pages, vector text preserved | 1 page, image scaled to printer DPI |
| Spool | Pages queued, status QUEUED | Same queue, same status |
| Device | Printer checks colour capability, rejects colour job on mono device with CapabilityException | Same check, passes |
| Result | Per-page ack, job COMPLETED | Per-page ack, job COMPLETED |
Failure modes I would name in the loop
A file renamed from .pdf to .png is caught by sniffing, and the job is rejected with UnsupportedFormatException before spooling. A truncated PDF renders some pages then throws RenderException; the spooler marks the job FAILED with the page number and does not send partial output to a second printer. A printer that goes offline mid-job surfaces as a timeout on DeviceConnection, which the spooler retries for that page only, up to a configured limit, then fails the job. Large files are streamed to the renderer in chunks rather than loaded whole, so a 2 GB scan does not exhaust the heap. Each of these is detectable from the job record, which is what an operator or an auditor needs.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12How would you validate file types and approach sanity, load and stress testing, including running tests in parallel?
Reported in Thales Software Engineer interview experience (May 2026)
The 90-second answer
I would treat file validation as a trust boundary, not a format check. Extension and declared MIME type are hints from the uploader. I validate the bytes, the structure, and the resource cost before the file reaches business logic. Then I test that boundary at three levels: sanity tests prove the happy path and obvious rejects work, load tests prove it holds at expected volume, and stress tests find where it breaks and how it fails.
For a Thales ingestion service, say operators upload mission data packages, XML reports, and images through a web service, that means a file can be rejected for three different reasons. It is not the type it claims to be, it is the right type but malformed or schema-invalid, or it is valid but too expensive to process. Each needs a different test and a different error code.
File type validation in practice
Check magic bytes first, then parse, then enforce limits. A PDF starts with %PDF-, a PNG with the 8-byte signature 89 50 4E 47 0D 0A 1A 0A, a ZIP (and therefore DOCX and XLSX) with PK\x03\x04. Never trust the filename. After the magic check, run the real parser in a sandbox with a timeout, because a file with correct magic can still be a parser exploit or a decompression bomb.
# Python 3.12, checked against CPython 3.12
import zipfile
from pathlib import Path
MAGIC = {
"pdf": b"%PDF-",
"png": b"\x89PNG\r\n\x1a\n",
"zip": b"PK\x03\x04",
}
MAX_BYTES = 25 * 1024 * 1024 # 25 MiB per file, example limit
MAX_UNCOMPRESSED = 200 * 1024 * 1024 # zip bomb guard
def validate(path: Path) -> str:
data = path.read_bytes()[:8]
if path.stat().st_size > MAX_BYTES:
raise ValueError("file_too_large")
kind = next((k for k, m in MAGIC.items() if data.startswith(m)), None)
if kind is None:
raise ValueError("unsupported_type")
if kind == "zip":
with zipfile.ZipFile(path) as zf:
total = sum(i.file_size for i in zf.infolist())
if total > MAX_UNCOMPRESSED:
raise ValueError("decompression_limit")
bad = zf.testzip()
if bad:
raise ValueError(f"corrupt_member:{bad}")
return kindThe test set for this is a corpus, not a handful of hand-made files. Keep valid samples per type, truncated files, files with correct magic and corrupt bodies, polyglots (valid PNG that is also valid ZIP), renamed executables, and archives nested three deep. Each corpus entry asserts the exact error code, because "rejects bad files" is not testable and unsupported_type versus corrupt_member drives different client behaviour.
Sanity, load, and stress are different questions
| Level | Question it answers | Example setup (hypothetical figures) | Pass criteria |
|---|---|---|---|
| Sanity / smoke | Does the pipeline work at all, and does it reject the obvious bad input? | 20 files: 5 valid per type, 5 wrong magic, 5 truncated, 5 oversize | Correct accept/reject and error code on every file, p95 under 500 ms per file |
| Load | Does it meet the service level at expected peak? | 50 concurrent uploads, 10 MiB average, sustained 10 minutes | p95 upload-to-stored under 2 s, error rate under 0.1%, no queue growth |
| Stress | Where does it break, and does it degrade cleanly? | Ramp concurrency 50 to 500, then file size to the 25 MiB cap | Sheds load with 429 or 413, never OOM-kills the worker, recovers within 60 s after load drops |
Load testing needs the production shape, not just volume. If real uploads are 80% XML at 200 KB and 20% images at 8 MB, a test that sends only small PDFs will miss the parser CPU bottleneck entirely. I would replay anonymised production metadata (size distribution, type mix, arrival rate) with k6 or Locust, and I would watch server-side metrics during the run: parser CPU per megabyte, temp disk usage, and connection pool saturation. A p99 that jumps from 180 ms to 4 s once the pool hits 20 connections is a finding. "It got slower" is not.
Stress testing deliberately goes past the cap. Oversize files, deeply nested archives, and a flood of concurrent parses should produce bounded failures: 413 for too large, 429 when the queue is full, and a circuit breaker on the parser pool. The failure mode I most want to rule out is a single 25 MiB zip expanding to 2 GB on disk and taking the node down for every other tenant.
Running tests in parallel
Parallelism cuts suite time but introduces shared-state failures, so I parallelise only tests that are isolated by construction. Each worker gets its own storage prefix or container, its own database schema or transaction, and generated filenames with a worker ID. No test reads a file another test wrote.
With pytest I would use pytest -n auto (pytest-xdist) and split by file so a slow parser test does not serialise a worker. With JUnit 5, junit.jupiter.execution.parallel.enabled=true with fixed parallelism. Two rules keep it honest. First, cap parallelism at the number of physical cores on the runner, because oversubscription makes timing-sensitive load tests meaningless. Second, never parallelise the load and stress runs themselves against a shared environment. Those run alone, on a dedicated environment, with the production-like data volume, or the numbers lie.
Flaky tests get quarantined after two failures in a week, not retried into green. A retry that passes on the second attempt hides a race between the validator and the storage layer, and in a safety-adjacent system that race is exactly what the test was supposed to catch.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Design and implement a peer-to-peer banking transfer system?
Reported in Thales Software Engineer interview experience (May 2026)
The 90-second answer
I would build this as a double-entry ledger, not as two balance updates. A transfer is one atomic transaction that debits the sender, credits the receiver, and writes an immutable journal entry that explains both sides. Balances are derived from that journal, or cached from it, never edited in place.
Assumptions I would state up front: one currency to start, both accounts in the same ledger database, and transfers are internal book transfers rather than SWIFT or card settlement. That keeps the core problem tractable. Cross-currency, external rails and sanctions screening then become separate services that plug into the same transfer record.
The API is POST /transfers with from_account, to_account, amount_minor, currency and a client supplied Idempotency-Key. Amounts are integer minor units, for example cents, never floating point. The server validates funds, account status and ownership, then commits debit and credit together or not at all. A retry with the same key returns the original transfer, it does not create a second one.
The ledger transaction
Concurrency is where this fails in practice. Two transfers out of the same account can both read a balance of 100.00 and both pass a funds check. Locking both rows in a consistent order prevents that and avoids deadlocks when two transfers cross between the same pair of accounts.
// Java 17, Spring JDBC. Amounts in minor units.
@Transactional
public TransferResult transfer(String key, long fromId, long toId, long amount) {
// Lock in account-id order to avoid deadlock between A->B and B->A.
long first = Math.min(fromId, toId);
long second = Math.max(fromId, toId);
jdbc.queryForObject(
"SELECT balance_minor FROM accounts WHERE id = ? FOR UPDATE", Long.class, first);
jdbc.queryForObject(
"SELECT balance_minor FROM accounts WHERE id = ? FOR UPDATE", Long.class, second);
long fromBalance = balanceOf(fromId);
if (fromBalance < amount) throw new InsufficientFundsException();
jdbc.update("UPDATE accounts SET balance_minor = balance_minor - ? WHERE id = ?", amount, fromId);
jdbc.update("UPDATE accounts SET balance_minor = balance_minor + ? WHERE id = ?", amount, toId);
long transferId = insertJournal(key, fromId, toId, amount); // two entries, one tx id
insertOutbox(transferId, "transfer.posted");
return new TransferResult(transferId, "POSTED");
}If the process crashes after the debit update but before commit, the database rolls both updates back. That is the whole point of doing it in one transaction. Splitting debit and credit into separate calls, or into separate services without a saga and reconciliation, leaves a window where money has left one account and arrived nowhere.
Idempotency and state
A client that times out after 2 seconds will retry. Without a key, the server cannot distinguish a retry from a deliberate second payment of, say, 250.00. Store key -> transfer_id, status, response for at least 24 hours and replay it.
| State | Meaning | Client action |
|---|---|---|
PENDING | Accepted, ledger transaction not yet committed | Poll GET /transfers/{id} |
POSTED | Debit and credit committed, journal written | Treat as final |
REJECTED | Validation, funds or account status failed | Read code, do not retry blindly |
REVERSED | Posted then compensated by a new reversing entry | Original entry stays in the journal |
Reversal matters in a regulated setting. You do not delete or edit a posted entry. You post a compensating entry with the opposite signs and a link to the original. That preserves the audit trail an auditor or a Thales customer in defence or finance would expect, and it keeps the sum of all journal entries equal to the sum of balances.
Worked trace, amounts in minor units. Account A holds 10,000, account B holds 0. A transfer of 2,500 arrives with key k1. The transaction locks A then B, checks 10,000 >= 2,500, writes A = 7,500, B = 2,500, inserts two journal lines totalling zero net, and commits. The retry with k1 800 ms later finds the stored result and returns the same transfer id with POSTED. No second debit occurs.
Failure modes I would name
Duplicate submission from a double click or a retry storm. Handled by the idempotency key and a unique constraint on it, so even a race to insert the same key fails safely.
Deadlock between simultaneous A to B and B to A transfers. Handled by locking in account-id order, as in the code above. Under contention, lock wait time is the metric to watch. If p99 lock wait climbs past a few hundred milliseconds, the account row is too hot and needs sharding or a queue per account.
Notification sent but transfer rolled back, or the reverse. Handled by the outbox pattern. The event is written in the same transaction as the ledger entries. A relay publishes it afterwards, so consumers only ever see committed transfers. Consumers themselves must be idempotent, because the relay can deliver twice.
Fraud and compliance checks that run after posting. In a real bank, KYC status, account freeze and AML screening run before posting, and a transfer that fails them is REJECTED before any money moves. If a check can only run asynchronously, the transfer stays PENDING and funds are held, not posted, until it clears.
What I would not build first
I would not start with a distributed ledger or a microservice per account. A single ledger database with row locking handles thousands of transfers per second for internal book transfers, and it gives you atomicity for free. I would split services only when a concrete limit appears, such as notification throughput or a separate compliance workload, and I would keep the ledger as the single writer of balances.
For testing, I would run concurrent transfer tests that assert the invariant directly: the sum of all balances never changes except through journal entries, no balance goes negative unless overdraft is an explicit product feature, and every posted transfer has exactly two journal lines. That invariant check catches the race conditions that unit tests miss.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Find the middle of a linked list and reverse strings in place?
Reported in Thales Software Engineer interview experience (December 2025)
The 90-second answer
For the list I would use slow and fast pointers. slow moves one node at a time and fast moves two. When fast can no longer move, slow is at the middle. That is one pass, O(n) time and O(1) extra space, and it needs no length count first.
For the string I would use two indices, left at 0 and right at the last position, swap the characters, then move inward until they meet. Also one pass and O(1) extra space if the string is mutable.
I would state the even-length convention up front. For a list of six nodes, returning the second middle (node 4) is the usual choice with the loop below. If the interviewer wants the first middle, I change one condition and say so.
Middle of a linked list (C++17)
struct ListNode {
int val;
ListNode* next;
ListNode(int v) : val(v), next(nullptr) {}
};
ListNode* middleNode(ListNode* head) {
if (!head) return nullptr;
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}Worked trace for 1 -> 2 -> 3 -> 4 -> 5 -> 6:
| Step | slow | fast | Check fast && fast->next |
|---|---|---|---|
| start | 1 | 1 | true |
| 1 | 2 | 3 | true |
| 2 | 3 | 5 | true |
| 3 | 4 | nullptr | false, stop |
slow is node 4. For 1 -> 2 -> 3 -> 4 -> 5 the same loop stops with slow at 3. For a single node it returns that node, and for an empty list it returns nullptr instead of dereferencing null.
The common bug is advancing fast without checking fast->next first. On an even-length list fast->next becomes null on the last step, so fast->next->next would crash. The guard in the while condition prevents that.
Reverse a string in place (C++17)
#include <string>
#include <utility>
void reverseString(std::string& s) {
std::size_t left = 0;
if (s.empty()) return;
std::size_t right = s.size() - 1;
while (left < right) {
std::swap(s[left], s[right]);
++left;
--right;
}
}Trace for "Thales" (indices 0 to 5):
| left | right | After swap |
|---|---|---|
| 0 | 5 | selahT |
| 1 | 4 | selahT (swap h and e gives sehl aT in place, final selahT) |
| 2 | 3 | selahT |
The loop stops when left >= right, so the middle character of an odd-length string is never swapped with itself. Empty and single-character strings return unchanged.
One limit worth naming: this reverses bytes. That is correct for ASCII and for std::string treated as a byte sequence, but it corrupts UTF-8 text with multibyte characters, since continuation bytes would be reordered. For user-facing Unicode text I would reverse by code point, not by byte, and accept the extra storage that requires. In Python the equivalent is s = s[::-1], which builds a new string, so the in-place constraint is really a C or C++ question.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15How many bits does an integer take up in Java and what is auto-boxing?
Reported in Thales Software Engineer interview experience (February 2026)
The 90-second answer
In Java, int is a primitive 32-bit signed integer in two's complement, so it ranges from -2,147,483,648 to 2,147,483,647. That size is fixed by the Java Language Specification. It does not depend on the platform, unlike C where int is commonly 32 bits but not guaranteed.
Auto-boxing is the compiler inserting a conversion between that primitive and its wrapper object, Integer, so you can write code that mixes the two. Boxing converts int to Integer with Integer.valueOf(int). Unboxing converts Integer back to int with Integer.intValue(). It was introduced in Java 5 in 2004 and it is purely a compile-time convenience. At runtime you still pay for an object allocation, except where the JVM reuses a cached instance.
| Type | Bits | Range |
|---|---|---|
byte | 8 | -128 to 127 |
short | 16 | -32,768 to 32,767 |
int | 32 | -2,147,483,648 to 2,147,483,647 |
long | 64 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
char | 16 | 0 to 65,535, unsigned |
Where it bites in practice
Three failure modes come up in real code, and I would name them in an interview because each one has a distinct symptom.
First, reference comparison. == on two Integer objects compares identity, not value. Integer.valueOf caches instances from -128 to 127, as required by the JLS, so comparisons inside that range can pass by accident and fail outside it. That makes the bug intermittent and data dependent.
// Checked against Java 17
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b); // false: two distinct objects
System.out.println(a.equals(b)); // true
Integer c = 100;
Integer d = 100;
System.out.println(c == d); // true: both from the -128..127 cache
Integer n = null;
int unboxed = n; // NullPointerException on unboxingSecond, a null unboxing throws NullPointerException even though no method call appears in your source. A Map<Integer, Integer> lookup that misses returns null, and assigning that result to an int variable fails at that line. The stack trace points at the assignment, which confuses people who did not realise unboxing happened.
Third, performance and overflow. Boxing in a tight loop, for example summing a List<Integer> of a million entries, allocates or at least dereferences wrapper objects where a primitive int[] would not. And int arithmetic wraps silently on overflow: Integer.MAX_VALUE + 1 gives Integer.MIN_VALUE, with no exception. If the value is a count, a byte offset, or money in minor units, I would either use long or use Math.addExact and handle the ArithmeticException explicitly.
So my rule of thumb: use int for arithmetic and loop variables, use Integer only where a reference type is required such as generics or a nullable map value, and when I do use it, compare with equals and guard against null before unboxing. That keeps the convenience of auto-boxing without letting it hide allocation, identity, or null costs.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Find the Longest Substring Without Repeating Characters?
Reported in Thales Software Engineer interview experience (April 2026)
The 90-second answer
Keep a window [left, right] that contains no repeated character and is the longest such window ending at right. Move right across the string once. When s[right] already occurred inside the window, jump left to one past its previous index. Otherwise the window just grows. Track the maximum window length seen.
That gives O(n) time and O(k) extra space, where k is the number of distinct characters in the window. It beats the O(n^2) check-every-substring approach, which at n = 100,000 needs roughly 10^10 character comparisons and will not finish in an interview time limit or a real service.
# Python 3.12
def longest_unique(s: str) -> int:
last = {} # char -> most recent index
left = 0
best = 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1
last[ch] = right
best = max(best, right - left + 1)
return bestThe invariant is what makes the jump safe. Every index before left is either outside the current window or would create a repeat inside it, so discarding it cannot remove a longer valid window ending at right. The condition last[ch] >= left matters: if the previous occurrence is already left of the window, it imposes no constraint and left must not move backwards.
Worked trace: abcaabcbb
| right | ch | last[ch] before | left after | window | best |
|---|---|---|---|---|---|
| 0 | a | - | 0 | a | 1 |
| 1 | b | - | 0 | ab | 2 |
| 2 | c | - | 0 | abc | 3 |
| 3 | a | 0 | 1 | bca | 3 |
| 4 | a | 3 | 4 | a | 3 |
| 5 | b | 1 | 4 | ab | 3 |
| 6 | c | 2 | 4 | abc | 3 |
| 7 | b | 5 | 6 | cb | 3 |
| 8 | b | 7 | 8 | b | 3 |
Result is 3, for example abc or bca. Note step 5: the second a at index 4 forces left to 4, so the window restarts rather than shrinking one character at a time.
Alternatives and when they fail
| Approach | Time | Space | Problem |
|---|---|---|---|
| Brute force, test every substring | O(n^2) | O(n) | Times out on long inputs |
| Sliding window with a set, shrink by one | O(n) amortised | O(k) | Correct, but more steps and easier to get the shrink loop wrong |
| Sliding window with last-index map, above | O(n) | O(k) | Needs a hash map for Unicode |
For plain ASCII in C, which comes up in embedded work, replace the map with a fixed int last[128] initialised to -1. That is O(1) lookup, bounded memory, and no allocation in the loop. For UTF-8 text, a byte array would be wrong because one character spans several bytes, so the map keyed by code point is the safer choice.
Two bugs show up in almost every attempt. Returning the substring instead of its length when the question asks for length, and setting left = last[ch] instead of last[ch] + 1, which leaves the duplicate inside the window. Test both with bbbbb (answer 1) and pwwkew (answer 3). An empty string should return 0 without special casing, which the code above already does.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Find the 4th highest score among N participants using an efficient approach rather than sorting?
Reported in Thales Software Engineer interview experience (April 2026)
The 90-second answer
First I would clarify one thing, because it changes the code: does "4th highest" count duplicates? With scores [95, 95, 90, 88], the answer is 88 if duplicates count, and 90 if you want the 4th distinct score. I will assume duplicates count unless the interviewer says otherwise, and I would state that assumption out loud.
For a fixed k = 4, a min-heap of size 4 gives O(N log k) time and O(k) extra space, which is O(N) here since log 4 is a constant. Sorting is O(N log N) and moves every element. The heap only ever keeps the current top 4, so the smallest of those 4 is the answer.
import heapq
def fourth_highest(scores):
heap = [] # min-heap, always holds the 4 largest seen so far
for s in scores:
if len(heap) < 4:
heapq.heappush(heap, s)
elif s > heap[0]:
heapq.heapreplace(heap, s)
return heap[0] if len(heap) == 4 else Noneheapq in Python is a min-heap, so heap[0] is the smallest element in the heap. That is exactly the 4th largest overall once the scan finishes. heapreplace pops the minimum and pushes the new value in one O(log k) step.
Worked trace
Scores in arrival order: [82, 95, 71, 88, 95, 64, 90]. Sorted descending they are [95, 95, 90, 88, 82, 71, 64], so the expected answer is 88.
| Score | Heap after step | Action |
|---|---|---|
| 82 | [82] | fill heap |
| 95 | [82, 95] | fill heap |
| 71 | [71, 82, 95] | fill heap |
| 88 | [71, 82, 88, 95] | fill heap, now full |
| 95 | [82, 88, 95, 95] | 95 > 71, replace 71 |
| 64 | [82, 88, 95, 95] | 64 < 82, skip |
| 90 | [88, 90, 95, 95] | 90 > 82, replace 82 |
Final heap[0] is 88. The heap never held more than 4 elements, even though 7 scores arrived.
Why this over the alternatives
| Approach | Time | Extra space | When I would pick it |
|---|---|---|---|
| Full sort, take index 3 | O(N log N) | O(N) for Timsort in CPython, O(1) for in-place sort | N is small, or I need the full ranking anyway |
| Min-heap, size k | O(N log k) | O(k) | k is small and fixed, streaming input, limited memory |
Quickselect / nth_element | O(N) average, O(N^2) worst case without randomised pivot | O(1) to O(N) depending on implementation | k is large (close to N/2), and I can mutate the array |
For k = 4 the heap wins on simplicity and on worst-case behaviour. Quickselect has a better average constant for large k, but its worst case and its mutation of the input make it a worse default for a streaming score feed. If the scores arrive one at a time from a network socket, the heap also answers after the first 4 elements without storing the rest, which sorting cannot do.
Failure modes and edge cases
N < 4: there is no 4th highest score. Returning None (or raising, depending on the contract) beats returning the minimum and letting the caller mistake it for a real rank. I would ask which behaviour the caller expects.
Distinct scores: if the interviewer wants distinct ranks, I need to skip values already in the heap before the s > heap[0] test, or track a seen set. That adds O(k) or O(N) space, so I would only add it when asked.
Ties at the boundary: with the strict > comparison, a score equal to heap[0] is skipped. That is correct for counting duplicates, because an equal score cannot displace the current 4th place. Using >= would churn the heap without changing the result.
Large N with a growing k: if the question later becomes "top 10%" instead of "top 4", the heap grows to O(N) and the advantage disappears. At that point I would switch to quickselect or a counting approach if scores have a bounded range, for example 0 to 100, where a frequency array gives O(N + range) time.
That is the answer I would give live: clarify duplicates, run a size-4 min-heap in one pass, and name the cases where sorting or quickselect would be the better tool.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18Reverse the order of words in a sentence?
Reported in Thales Software Engineer interview experience (April 2026)
The 90-second answer
I would ask what counts as a word separator before coding. The usual interview assumption is single spaces between words, punctuation stays attached to its word, and I can return a new string. Under that assumption the answer is tokenise, reverse the token list, join with single spaces.
def reverse_words(s: str) -> str: # Python 3.12
return " ".join(s.split()[::-1])str.split() with no argument splits on any run of whitespace (space, tab, newline), discards leading and trailing whitespace, and returns an empty list for an empty or all-whitespace string. Reversing that list and joining gives the result in one pass over the tokens.
| Input | Output | Why |
|---|---|---|
the quick brown fox | fox brown quick the | Four tokens reversed |
hello world | world hello | Extra spaces collapsed, edges trimmed |
hello, world! | world! hello, | Punctuation stays with its word |
| `` (empty) | `` | No tokens, no error |
one | one | Single token is its own reverse |
Complexity and alternatives
Let n be the length of the string and w the number of words. The split approach above is O(n) time and O(n) extra space in the worst case, because the token list plus the joined result hold roughly the input size again. For a 1 MB log line that is about 2 MB of transient allocation, which is fine on a server and wasteful on a small embedded target.
| Approach | Time | Extra space | When I would pick it |
|---|---|---|---|
split then reverse then join | O(n) | O(n) | Default. Readable, handles irregular whitespace |
| Scan from the end, slicing each word | O(n) | O(n) for the result | Preserving exact spacing matters and I want to avoid a token list |
| Reverse all characters in place, then reverse each word in place | O(n) | O(1) | Fixed C buffer, no allocation allowed, caller accepts mutation |
The in-place method is the one to mention if the interviewer pushes on constraints, as Thales code often runs in C with fixed buffers. Reverse the whole buffer, then find each word boundary and reverse that span. It needs a mutable char array, a length or NUL terminator, and care with the final word having no trailing space. It also destroys the original, so I would only offer it when the contract says the buffer is scratch space.
Failure modes I would name
Multiple spaces and tabs change the answer depending on the contract. split normalises them to single spaces. If the task is to preserve spacing exactly, for example aligning columns in a formatted report, that normalisation is a bug and I need the scan-from-the-end version that copies the gaps verbatim.
Unicode is the other trap. Splitting on whitespace is safe for most languages, but reversing by character index breaks combining marks and grapheme clusters. A string with an accented character written as a base letter plus a combining accent can render incorrectly after a naive per-character reversal. The token approach avoids that because it never reverses inside a word.
Punctuation and hyphenation need a stated rule. well-known is one token under whitespace splitting. If the interviewer expects known-well, the definition of word has changed and I would switch to splitting on non-alphanumeric boundaries, which is a different function.
Finally, very long input. Building a token list for a 100 MB file line risks memory pressure and a long pause. If the input arrives as a stream, I would read it in chunks, emit words from the end only if it is seekable, or admit that reversing word order fundamentally needs the whole input before the first output word is known. That admission, plus the O(n) bound, is usually what the interviewer is listening for.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19How would you optimize slow SQL queries?
Reported in Thales Software Engineer interview experience (April 2026)
The 90-second answer
I would not start by adding an index. I would start by reproducing the slowness with production-like data and reading the plan. In PostgreSQL I check pg_stat_statements for total time, calls and mean time, then run EXPLAIN (ANALYZE, BUFFERS) on the exact query with the exact parameters from the slow log. That tells me whether the cost is a sequential scan, a bad join order, a sort, or rows returned to the application. Only then do I change the query, the schema, or both, and I re-run the same plan to prove the change helped.
Assume a ground station telemetry service at Thales, PostgreSQL 16, a table telemetry(device_id, ts, value) with 2.4 million rows. The dashboard query is:
-- Before: function on the column defeats a plain index, and SELECT * pulls payloads
SELECT *
FROM telemetry
WHERE device_id = 'GS-14'
AND date(ts) = DATE '2026-04-10'
ORDER BY ts DESC
LIMIT 100;A worked trace, figures from a labelled test copy at that size:
| Step | Plan node | Rows | Time | Reading |
|---|---|---|---|---|
| 1 | Seq Scan on telemetry | 2,400,000 scanned, 18,200 matched | 340 ms | No usable index path |
| 2 | Sort | 18,200 | 22 ms | Sorting a day of data for 100 rows |
| 3 | Limit | 100 | 0.1 ms | Work already done |
The fix has two parts. Rewrite the predicate as a range so an index can be used, and add a composite index that matches the filter and the ordering:
-- After
SELECT ts, value
FROM telemetry
WHERE device_id = 'GS-14'
AND ts >= TIMESTAMPTZ '2026-04-10 00:00:00+00'
AND ts < TIMESTAMPTZ '2026-04-11 00:00:00+00'
ORDER BY ts DESC
LIMIT 100;
CREATE INDEX CONCURRENTLY idx_telemetry_device_ts
ON telemetry (device_id, ts DESC)
INCLUDE (value);Re-running the plan gives an Index Scan using that index, about 100 rows visited, 9 ms total, and buffers shared hit in the low hundreds instead of 31,000. CONCURRENTLY matters in a live service because a plain CREATE INDEX takes a lock that blocks writes. I would still schedule it in a maintenance window and watch replication lag while it builds.
What else I check before touching the schema
| Suspect | Test | Typical fix |
|---|---|---|
| --- | --- | --- |
| N+1 queries from the ORM | Count statements per request in logs | One join or WHERE id IN (...) batch |
OFFSET pagination on a large table | Plan shows scanning and discarding rows | Keyset pagination on (ts, id) |
| Stale statistics after bulk load | last_analyze old, plan picks wrong join order | ANALYZE the table, check pg_stats |
| Low selectivity filter | Index scan still visits most of the table | Drop the index, filter differently, or partition by time |
| Type mismatch, for example text parameter against a bigint column | Plan shows a cast and no index scan | Fix the parameter type in the application |
Trade-offs and failure modes
Every index speeds reads and taxes writes. A composite index on a high-ingest telemetry table adds storage and slows inserts, and three or four overlapping indexes can make a bulk load miss its window. I measure insert throughput before and after, and I drop indexes that pg_stat_user_indexes shows as unused over a full reporting cycle.
The common failure is an index the planner ignores. Causes I have seen: a function wrapped around the indexed column, a parameter type that forces a cast, statistics that say the table is tiny, or a filter so unselective that a sequential scan really is cheaper. The plan after the change is the only proof. A second failure is fixing the query in staging with 10,000 rows and discovering in production that the sort spills to disk at 2.4 million rows. That is why I test at production volume, or at least with EXPLAIN costs scaled by row count, and I check work_mem spill in the plan output.
In a regulated Thales programme I would also treat the change as a controlled release: migration reviewed, rollback plan stated, and the before and after plans attached to the change record. Performance work that cannot be audited is hard to defend when a safety case or a customer audit asks why a schema changed.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20How do you insert a node into a linked list?
Reported in Thales Software Engineer interview experience (September 2025)
The 90-second answer
Insertion is pointer surgery. You allocate or reuse a node, set its next to whatever followed the insertion point, then point the predecessor at the new node. Order matters. If you overwrite the predecessor first, you lose the rest of the list.
For a singly linked list in C, the three cases are head, middle, and tail. Head insertion is O(1) and needs no search. Middle and tail need a walk to the predecessor, so O(n) time and O(1) extra space. Tail insertion is O(1) only if you also keep a tail pointer.
// C17, singly linked list. Returns 0 on success, -1 on allocation failure.
struct Node { int value; struct Node *next; };
int insert_after(struct Node **head, struct Node *prev, int value)
{
struct Node *node = malloc(sizeof *node);
if (!node) return -1;
node->value = value;
if (!prev) { // insert at head
node->next = *head;
*head = node;
} else { // insert after prev
node->next = prev->next;
prev->next = node;
}
return 0;
}That handles the empty list too. With *head == NULL and prev == NULL, the new node becomes the head and its next is NULL.
Worked trace
Start: 10 -> 20 -> 30 -> NULL. Insert 25 after the node holding 20.
| Step | Action | List after step |
|---|---|---|
| 1 | node = {25, ?} | 10 -> 20 -> 30 -> NULL (node unlinked) |
| 2 | node->next = prev->next i.e. 25 -> 30 | 10 -> 20 -> 30 -> NULL |
| 3 | prev->next = node i.e. 20 -> 25 | 10 -> 20 -> 25 -> 30 -> NULL |
Swap steps 2 and 3 and step 3 writes 20 -> 25 but 25->next still holds garbage or NULL, so 30 is orphaned. That lost-node bug is the most common failure in review, and it leaks memory because nothing can reach 30 to free it.
| Case | Predecessor | Time | Extra state needed |
|---|---|---|---|
| Head | none, update *head | O(1) | none |
| Middle | node before insertion point | O(n) search, O(1) splice | none |
| Tail | last node | O(n) search, O(1) with tail pointer | tail pointer to maintain |
Failure modes I would name in the loop
First, allocation failure. In Thales-style embedded or safety-critical code, malloc may be banned or may fail under memory pressure, so returning an error code as above is not optional. A fixed pool allocator with a bounded node count is often preferred, because exhaustion is then predictable at startup rather than at runtime.
Second, a stale predecessor. If another thread or interrupt handler frees or moves prev between the search and the splice, you write through a dangling pointer. The fix depends on context: hold a lock across search and splice, or use a hazard pointer or epoch scheme if the list is lock-free. A plain list with no synchronisation is only safe for single-threaded use.
Third, the dummy head trick. Passing a sentinel node whose next is the real head removes the special case for head insertion, because every insertion has a predecessor. It costs one extra node and complicates iteration slightly, but it removes a whole branch and the bug class that comes with it. I would mention it as the alternative I reach for when head insertion is frequent.
If asked to extend it, I would add a tail pointer for append-heavy workloads, switch to a doubly linked list when deletion by node pointer is needed in O(1), and state the invariant I maintain after every call: the list is acyclic, every node is reachable from *head, and no node is reachable twice.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Why did you choose to apply to Thales specifically?
Reported in Thales Software Engineer interview experience (June 2026)
The 90-second answer
I applied because the kind of software I want to keep building is the kind Thales builds: long-lived, safety-critical systems where a bug is not a bad user review. My last two years were on [embedded/distributed system, e.g. telemetry and control for industrial equipment], and I kept hitting the same ceiling. The product shipped, but the hard problems were treated as someone else's job. At Thales, that work is the product. Avionics, radar, secure communications, space systems, and rail signalling all live or die on determinism, traceability, and security, and the software team owns those properties from design through certification and into service.
I also looked at the structure before applying. Thales is not a generalist contractor that happens to have a defence logo. The groups are distinct: Aerospace, Defence and Security, Digital Identity and Security, and Transport, plus Thales Alenia Space for payloads and ground systems. That matters to me because I want depth in one domain for several years, not a new stack every six months. A flight management or secure radio codebase that stays in service for 15 to 20 years rewards the engineer who understands why a decision was made in 2019, and punishes the one who rewrites it without that context. That is the trade I want.
The second reason is how Thales handles constraints I have already worked under. Export controls, classified programmes, and customer-specific variants mean you cannot just push to main. You design for audit, for degraded hardware, and for a customer who will run your code on equipment you will never see. I have worked under IEC 61508 style processes on a smaller scale, with requirements traced to tests and a strict change board. I want to do that at a scale where the process is enforced by the domain, not by a manager's preference.
Where my experience maps
| What I have done | Where it lands at Thales | What I still need to learn |
|---|---|---|
| C/C++ on constrained hardware, fixed latency budgets, watchdog recovery | Avionics and defence embedded software, radar and sonar signal processing | DO-178C certification evidence and formal verification tooling |
| Distributed services with audit logs and offline operation | Secure communications and transport signalling, where nodes must keep running when disconnected | Cryptographic key management and classified development environments |
| Long-term maintenance of a system with multiple customer variants | Space and ground systems, where a patch may take months to qualify and deploy | Radiation tolerance, real-time operating systems at flight level, and systems engineering across hardware teams |
That last column is deliberate. I am not claiming I already know Thales's certification stack. I am claiming the gap is specific and learnable, and that I have the habits that transfer: writing code a reviewer can trace to a requirement, testing failure modes instead of happy paths, and documenting why an interface cannot change.
I would rather spend the next few years inside that loop than move to a role where speed is the only measure. If the team I join is working on, say, secure communications, I can contribute on day one on the distributed systems side and grow into the domain side. If it is avionics, the embedded work transfers and I will pick up the certification discipline on the job. Either way, the reason is the same: Thales builds software that has to be right, for a long time, under constraints you cannot negotiate away. That is the work I chose to apply for.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22How do you handle a difficult client?
Reported in Thales Software Engineer interview experience (March 2026)
The 90-second answer
I treat "difficult" as a signal, not a personality label. Usually it means the requirement is ambiguous, the deadline and the scope do not fit together, or the client is under pressure and wants me to bypass the process that protects both of us. My job is to keep the relationship intact while keeping the decision traceable.
I start by separating the person from the request. I listen, then restate what I heard in writing and check that restatement before I argue with it. Next I anchor the request to the baseline we already agreed: the contract, the requirements document, the safety case, and the current test evidence. If the request fits inside that baseline, I can just do it. If it changes scope, cost, schedule, or a safety property, it goes through change control, with options and consequences written down. If it asks me to ship something unsafe, non-compliant, or outside my authority, I escalate early to my line manager and the customer's technical lead, with the facts, not the frustration.
That last point matters at Thales. A verbal "yes" in a corridor can become a contractual commitment, and an undocumented workaround can break traceability that an auditor or a regulator will ask for two years later. Writing it down is not bureaucracy for its own sake. It is how the next engineer, and the client, can see why a decision was taken.
A concrete trace
Say a customer programme manager asks us, two weeks before a delivery milestone, to include a new display mode and skip the full regression run because "the demo is the real test." I would not refuse on the spot and I would not agree on the spot either.
| Step | What I do | Artefact left behind |
|---|---|---|
| 1 | Restate the ask: new mode in, regression out, same date | Email summary confirmed by the client |
| 2 | Check the baseline: display mode is a new requirement, regression is a contractual exit criterion | Requirement IDs and test plan references |
| 3 | Price the options honestly | Options table, see below |
| 4 | Put the chosen option through change control | Signed change record with traceability links |
| 5 | Implement, then run the agreed verification | Test report tied to the change ID |
The options table is where difficult conversations usually settle down, because it moves the argument from who is being awkward to what each choice costs.
| Option | Schedule effect | Risk |
|---|---|---|
| Ship the mode, run full regression | Milestone slips by 3 weeks (hypothetical estimate from our last similar change) | Lowest. Evidence matches the safety case. |
| Ship the mode, run targeted tests only | Milestone holds | Medium. We document the residual risk and the client accepts it in writing. |
| Defer the mode to the next release | Milestone holds, scope moves | Lowest technical risk, but the client loses the feature they wanted. |
For the arithmetic, a late change is rarely just the coding time. In this example, rework plus re-verification might be 2 engineers for 3 weeks, plus a regression run of roughly 400 automated tests. If we skip that run to save 3 weeks now, we are not saving the effort. We are converting it into unquantified risk that surfaces at acceptance, when fixing it costs more and the client has less room to manoeuvre.
How I record the decision
I keep the record small enough that people actually fill it in, but structured enough that it survives a handover. In our tooling that looks like this:
from dataclasses import dataclass
@dataclass
class ChangeDecision:
change_id: str # e.g. "CR-1042"
request: str # client's words, restated
baseline_refs: list[str] # requirement and contract clause IDs
options: list[str] # options considered, not just the winner
decision: str # chosen option and who approved it
verification: str # tests or analysis that will evidence itIf a field is empty, the decision is not done. That rule has saved me more than once, because it forces the conversation about verification to happen before the code, not after the complaint.
Failure modes I watch for
Agreeing verbally to keep the meeting pleasant, then discovering the client logged it as a commitment. Letting a request bypass the technical lead because it arrived directly to a developer, which splits the record. And treating every request as a formal change, which annoys the client when a simple clarification would do. The skill is calibration: clarify fast, formalise only when scope, safety, cost, or schedule actually moves.
If the client is abusive or the pressure is personal rather than technical, I bring in my manager or the account lead rather than absorbing it alone. That is not escalation as a threat. It is how I keep the technical discussion honest and keep the relationship recoverable.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23What are the different ways to inject a dependency in Java with Spring?
Reported in Thales Software Engineer interview experience (March 2026)
The 90-second answer
Spring supports constructor, setter, field and method injection. In a Thales codebase I would use constructor injection by default and treat the others as exceptions that need a reason. Constructor injection makes dependencies explicit in the signature, keeps fields final, fails fast at startup if a bean is missing, and lets me instantiate the class in a plain unit test with new OrderService(fakeGateway) and no Spring context. Field injection hides the dependency list, prevents final, and forces tests to use reflection or a full context. Setter injection is defensible for genuinely optional or mutable collaborators. Method injection is for lifecycle callbacks or a collaborator that is only needed for one call.
// Spring Boot 3.3, Java 21. Single constructor: no @Autowired needed.
@Service
public class OrderService {
private final PaymentGateway gateway;
private final AuditLog auditLog;
public OrderService(PaymentGateway gateway, AuditLog auditLog) {
this.gateway = gateway;
this.auditLog = auditLog;
}
public OrderId place(OrderRequest request) {
OrderId id = gateway.authorise(request);
auditLog.record(id, request);
return id;
}
}
// Unit test, no container, no reflection:
OrderService service = new OrderService(new FakeGateway(), new FakeAuditLog());| Style | How it looks | When it is acceptable | Main cost |
|---|---|---|---|
| Constructor | One constructor, or @Autowired on one of several | Default for required collaborators | Circular references fail at startup, which is usually a design error to fix |
| Setter | @Autowired on a setter method | Optional dependency, or a collaborator that must be replaceable after construction | Object is usable in an incomplete state if the setter is never called |
| Field | @Autowired or @Inject on a field | Legacy code, or framework-managed types you do not construct | Hidden dependencies, non-final fields, poor testability |
| Method | @Autowired on any method | One-off collaborator, or a callback such as @PostConstruct style initialisation | Dependency is invisible in the constructor, easy to miss in review |
How Spring picks the bean
With one constructor Spring uses it implicitly. With several constructors, annotate the one to use with @Autowired. If two beans of the same type exist, injection fails with NoUniqueBeanDefinitionException unless you disambiguate. @Qualifier("card") selects by bean name, @Primary marks the default. For a dependency that may be absent, use Optional<PaymentGateway> or ObjectProvider<PaymentGateway> in the constructor instead of a setter, so the optionality is visible in the signature.
public OrderService(Optional<PaymentGateway> gateway) {
this.gateway = gateway.orElseThrow(() -> new IllegalStateException("PaymentGateway bean missing"));
}@Resource from Jakarta Annotation is the other common variant. It injects by name by default, so @Resource(name = "cardGateway") differs from @Autowired, which matches by type first. Mixing both in one codebase causes confusion in reviews, so pick @Autowired or @Inject and stay with it.
Failure modes I watch for
Circular dependencies: A needs B and B needs A. Constructor injection exposes this immediately, and Spring Boot 2.6 and later prohibit circular references by default. Setter or field injection can paper over it by creating a half-initialised proxy, which then fails intermittently depending on creation order. In safety related code that nondeterminism is unacceptable, so I break the cycle by extracting a third bean or using an event.
Mutable state after construction: a setter that can be called at any time lets a test or another bean swap a collaborator mid-flight. If a setter exists for an optional dependency, I make the field nullable, document the default behaviour, and add a test for the absent case.
Test cost: field injection looks shorter in production code and costs more in every test. A class with four field-injected collaborators needs a Spring context or reflection helpers to test one method. That cost compounds across a large service, which is why constructor injection is the house rule in teams I have worked with, with setter injection reserved for optional collaborators and field injection removed during refactors.
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 are your strengths and weaknesses?
Reported in Thales Software Engineer interview experience (February 2026)
The 90-second answer
My main strength is finding and fixing defects in concurrent code under time pressure, and proving the fix with a test that fails before it and passes after it. My main weakness used to be estimating integration work on unfamiliar hardware, so I now timebox a spike before I commit to a date. Both are relevant here because a lot of Thales software has to be correct on the first deployment, traceable to a requirement, and maintainable by someone who did not write it.
Strength, with evidence
In my last role I owned a telemetry ingestion service in Java, about 40,000 messages a minute, where a race between a reconnect thread and a flush thread dropped roughly one batch in 2,000. I reproduced it with a stress harness that forced reconnects every 200 ms, added a failing assertion on sequence numbers, then moved the flush to a single owner thread and made the handoff queue bounded with explicit backpressure. The drop rate went to zero over a 72 hour soak, and the harness stayed in the repo as a regression test. That pattern, reproduce first, change one thing, keep the reproducer, is how I work on anything where a bug report is a stack trace and a hunch.
| Strength | Evidence | Why it matters in a regulated codebase |
|---|---|---|
| Concurrency and failure analysis | Race found by sequence assertion, fixed by single-owner flush, verified by 72 hour soak | Fewer field escapes, and the fix can be reviewed against a failing test |
| Testable design | Property tests for a parser, contract tests for a REST client, coverage on error paths rather than line count | Requirements trace to tests, which reviewers and auditors can follow |
| Clear handover writing | Design notes with assumptions, rejected alternatives, and rollback steps | Code survives staff rotation and configuration audits |
I am also comfortable reading a specification closely and asking what it does not say. On that same service, the spec said messages were at least once, and the original code assumed exactly once. Naming that gap early saved a redesign later.
Weakness, and what I changed
I underestimated hardware in the loop integration. On a project with a simulator, I planned three days for connecting a new sensor feed because the software interface was done. The simulator clock ran at a different rate, timestamps drifted, and I lost a week. I had treated the interface as the whole job.
I do not claim that is fixed by trying harder. I changed the process. Before committing to an estimate on unfamiliar integration, I run a half day spike that connects the real thing, even in a crude way, and I write down the three unknowns most likely to move the date. If the spike shows a clock or ordering problem, the estimate includes a week for it or the scope is cut. On the next integration I did that, found a timestamp drift in the spike, and the delivery landed on the revised date instead of slipping.
| Before | Now | Measurable result |
|---|---|---|
| Estimated from the interface document | Half day spike against the real simulator or device | Unknowns listed before the commitment |
| Reported slippage when it appeared | Flagged the drift risk in the first week | Date moved once, early, with evidence |
| Kept integration notes in my head | Short note with assumptions and open questions | A teammate could pick it up without me |
I still tend to go deep on a hard bug before asking for a second pair of eyes. I set a rule for myself: after two hours without a new hypothesis, I write up what I have tried and ask someone to poke at it. That has cut a couple of investigations from days to an afternoon.
If I joined Thales, I would lean on the first strength from day one, which is careful, test backed work in a codebase where changes go through review and configuration control. On the weakness, I would keep using spikes and early flags, because in safety related work a late surprise costs far more than an early awkward conversation about a date.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25Explain the SDLC processes you have used?
Reported in Thales Software Engineer interview experience (January 2026)
The 90-second answer
I have worked in two SDLCs, and I choose between them based on how safety-critical and how changeable the software is. For safety-critical work I used a V-model aligned to DO-178C, the avionics standard Thales builds to. For internal tooling and customer-facing services I used Scrum with a DevSecOps pipeline. The difference is not ceremony for its own sake. It is where verification happens and what evidence you can produce when an auditor, or a regulator, asks why a line of code is safe to fly.
In the V-model, every level on the left has a matching test level on the right. Requirements are not handed over and forgotten. Each requirement gets an ID, a design element, code, and a test that traces back to it. A change after design freeze goes through a change control board, because changing a requirement invalidates the tests below it.
In Scrum, the same traceability exists but it is lighter. A ticket links to a pull request and to automated tests in CI. The pipeline blocks merge if coverage, static analysis, or a security scan fails. That is enough when the cost of a bug is a rollback, not an incident report.
How the models compare
| Model | Best fit | Verification point | Main risk |
|---|---|---|---|
| Waterfall | Fixed contract, hardware delivery dates | End of each phase | Late discovery of a requirements error |
| V-model | DO-178C DAL A/B, IEC 61508 SIL 2+ | Each left level paired with a right level | Cost of change after design freeze |
| Scrum | Product software, changing user needs | Every sprint, via CI | Scope creep without a definition of done |
| DevSecOps | Continuous delivery, cloud services | Every merge, via pipeline gates | Pipeline becomes the bottleneck if gates are slow |
I would not use pure Waterfall for a product whose requirements will move. I would not use continuous deployment for DAL A flight software. The model follows the consequence of a defect.
Traceability in practice
A concrete example from a DO-178C project. Requirement REQ-114 stated that the display shall update within 100 ms of a sensor reading. That produced design item DES-207, a cyclic task with a 50 ms period, and test TC-331, which injected a sensor value and measured the display latency.
| Artefact | ID | Link | Evidence |
|---|---|---|---|
| Requirement | REQ-114 | Parent of DES-207 | Requirements database, version 4.2 |
| Design | DES-207 | Implements REQ-114 | Design document, reviewed by independent verifier |
| Code | display_task.c | Implements DES-207 | Git commit a91f3c, static analysis clean |
| Test | TC-331 | Verifies REQ-114 | Measured 62 ms, pass, recorded in test report |
When a developer proposed changing the period to 80 ms to save CPU, the impact analysis was mechanical. REQ-114 still passed on paper, but TC-331 had to be re-run and the timing analysis for DES-207 had to be redone. The change board approved it only after that evidence existed. That is the process working. Without it, you have code that probably still meets the requirement and no way to prove it.
The DevSecOps version of the same idea
For a non-critical service I ran, the pipeline enforced the same principle with less paperwork:
# .gitlab-ci.yml, checked against GitLab CI 16.x
stages: [build, test, scan, deploy]
test:
stage: test
script: ["pytest -q", "coverage report --fail-under=80"]
scan:
stage: scan
script: ["semgrep --error --config auto"]
deploy:
stage: deploy
needs: [test, scan]
script: ["./deploy.sh"]
only: [main]A merge that fails tests or the scan never reaches deploy. That is a gate, not a suggestion. The failure mode I saw was a scan rule that flagged every generated file, so developers started bypassing the pipeline. We fixed it by excluding generated paths and adding a 10 minute timeout alert, because a gate that is routinely bypassed is worse than no gate. It teaches people to ignore it.
Failure modes I watch for
Late integration in Waterfall. Two teams build to a design for six months, then discover their interfaces disagree. The V-model reduces this by testing interfaces at integration level early, but only if the test environment exists. I have seen projects where the hardware simulator arrived two months late, so integration testing was compressed into the final month and defects clustered there.
Requirements churn in Scrum. If the product owner changes acceptance criteria mid-sprint without updating the ticket, the team builds to the old criteria and the demo fails. The fix is boring. The ticket is the contract for that sprint, and changes go through re-estimation.
Audit findings in regulated work. The most common one is a test that passes but does not trace to a requirement, or a requirement with no test. A traceability matrix run in CI catches both. I ran a script that exported requirements and tests from the database and failed the build if any DAL B requirement had zero linked tests. That turned an audit surprise into a build failure, which is cheaper.
If I joined Thales, I would expect the V-model discipline for safety-critical products and the pipeline discipline for everything else, and I would be explicit with the team about which one applies to the code in front of us before we start writing it.
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: