
Real Interview Questions for the Software Engineer at Amadeus
NewInterview Q&A
Q&A-1Implement a function that takes a list of flight segments and returns all possible direct flight connections between any two airports in the list?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
I would clarify one word first: direct means a single segment with no intermediate airport and no layover to validate. So the task is to group segments by ordered pair (origin, destination) and return every segment for each pair, sorted by departure. If the interviewer meant one-stop connections, the grouping is the first step and I would add a second pass later.
Assumptions I would state out loud: airport codes are IATA codes normalised to upper case, datetimes are timezone-aware, and a segment with arrival <= departure or origin == destination is bad data and should raise rather than be silently dropped. In a feed from a GDS that silence hides a parsing bug until it reaches pricing.
from dataclasses import dataclass
from datetime import datetime
from collections import defaultdict
@dataclass(frozen=True)
class FlightSegment:
origin: str
destination: str
departure: datetime
arrival: datetime
flight_no: str = ""
def direct_connections(segments: list[FlightSegment]) -> dict[tuple[str, str], list[FlightSegment]]:
grouped: dict[tuple[str, str], list[FlightSegment]] = defaultdict(list)
seen: set[tuple] = set()
for s in segments:
origin, destination = s.origin.strip().upper(), s.destination.strip().upper()
if origin == destination:
raise ValueError(f"origin equals destination: {s}")
if s.arrival <= s.departure:
raise ValueError(f"arrival not after departure: {s}")
# Drop exact duplicates that arrive twice from a GDS feed.
key = (origin, destination, s.departure, s.arrival, s.flight_no)
if key in seen:
continue
seen.add(key)
grouped[(origin, destination)].append(s)
for flights in grouped.values():
flights.sort(key=lambda s: (s.departure, s.arrival))
return dict(grouped)Trace on a small input:
| Segment | Pair key | Result |
|---|---|---|
JFK -> LHR 08:00-20:00 VS3 | (JFK, LHR) | first entry |
JFK -> LHR 09:30-21:30 VS4 | (JFK, LHR) | appended, sorted after VS3 |
LHR -> JFK 10:00-13:00 VS3 | (LHR, JFK) | separate key, direction matters |
JFK -> CDG 08:00-10:00 AF9 | (JFK, CDG) | separate key |
JFK -> LHR 08:00-20:00 VS3 (repeat) | (JFK, LHR) | dropped by seen |
That gives {(JFK, LHR): [VS3, VS4], (LHR, JFK): [VS3], (JFK, CDG): [AF9]}.
Complexity and scale
Grouping is O(n) average time and O(n) extra memory for the output plus the seen set. Sorting each bucket costs O(k log k) where k is flights on that pair, so total O(n log n) worst case when every segment shares one pair. For 1 million segments that is fine in Python if the output itself is not materialised as a huge dict of lists for a network call. At Amadeus scale I would stream instead: sort externally by (origin, destination, departure) and emit groups as they close, which keeps memory near O(k) for the largest pair rather than O(n).
Where this breaks
Naive datetimes are the common failure. Two segments that look ordered in local time can invert once converted to UTC, so I would reject naive datetimes at the boundary or convert with the airport timezone before comparing. The second failure is output size: the number of distinct pairs can approach n in sparse data, and returning all of them to a caller that only needs one route wastes bandwidth. I would add an optional origin filter or a generator variant for that case. If the interviewer then asks for one-stop connections, I reuse the same index: for each arrival, binary search the destination bucket of the arrival airport for departures at or after arrival + min_layover, which avoids the O(n^2) pairwise scan.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Design a system to efficiently cache and serve flight schedules and availability data to thousands of travel agencies globally, handling cache invalidation and data freshness?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
I would split the problem in two before picking a cache. Flight schedules change rarely and predictably. Availability changes every time a seat is sold, held or released. Treating both with the same TTL either serves stale seats or hammers the inventory system.
So I would build two paths behind one API. Schedules go through a long-lived, versioned cache at the edge. Availability goes through a short-lived regional cache with event-driven invalidation from the inventory service, and it never pretends to be authoritative for booking.
Assume, as a worked example, 5,000 agencies, peak 20,000 availability queries per minute (about 333 QPS), and 2,000 schedule queries per minute. That is small enough for regional clusters, large enough that a cache miss storm matters. If the real numbers are 10x, the shape stays the same and the cluster count grows.
Schedules: version, do not expire
A schedule is keyed by route, date and version, for example sched:AMS:JFK:2026-09-14:v17. The schedule service publishes a new version when an airline files a change. The API resolves the current version pointer, serves the snapshot from CDN with Cache-Control: public, max-age=86400, immutable for the versioned object, and keeps the previous version for rollback.
Invalidation is then a pointer flip, not a purge. Clients that cached v16 keep a coherent timetable until they re-resolve. That avoids the classic failure where half the edge nodes have the new departure time and half have the old one during a purge.
Availability: short TTL plus events
Availability is different. I would cache per flight and cabin, avail:KL0643:2026-09-14:Y, with a 30 to 60 second TTL as a backstop. The primary invalidation is an event from inventory: seat sold, hold created, hold expired, seat released. The consumer deletes or updates that one key and increments a per-flight generation counter.
# Python 3.12, checked against Redis 7 semantics
def on_inventory_event(event, redis):
key = f"avail:{event.flight}:{event.date}:{event.cabin}"
pipe = redis.pipeline()
pipe.delete(key) # next read repopulates from inventory
pipe.incr(f"gen:{event.flight}:{event.date}")
pipe.expire(f"gen:{event.flight}:{event.date}", 3600)
pipe.execute()Deleting rather than updating in the consumer keeps one writer of truth. The next read repopulates from the inventory service, so a dropped event only costs staleness until the TTL expires.
| Concern | Schedule | Availability |
|---|---|---|
| --- | --- | --- |
| Change rate | Days to weeks | Seconds |
| Cache TTL | 24 h on versioned object | 30-60 s, event invalidated |
| Invalidation | Publish new version, flip pointer | Delete key on inventory event |
| Stale tolerance | Low, but versioned so coherent | 60 s acceptable for search, never for final booking |
| Origin load on miss | Snapshot store, cheap | Inventory service, expensive, so stampede protection matters |
Freshness and the booking boundary
Search results can be 60 seconds stale. A booking cannot. So the flow is: cached availability for search and pricing display, then a synchronous, uncached inventory check at hold and ticket time. The API returns generated_at and a stale: true flag when serving from cache past a soft threshold, and agencies can set max_staleness_seconds on the request. If they ask for 0, we bypass the cache.
That boundary is the failure mode interviewers probe. If an agency sells the last seat from a stale cache entry, the hold call fails at inventory and we return a clear seat_unavailable with a fresh availability snapshot, rather than letting the cache invent inventory.
Stampede and regional failure
When a popular flight key expires, 333 QPS can turn into 333 simultaneous origin calls. I would use request coalescing in the API layer: one caller fetches, others wait briefly or get stale data with stale-while-revalidate. Add jitter to TTLs so keys do not expire in lockstep, and set a per-key lock with a short timeout in Redis.
Regionally, I would run cache clusters in the regions where agencies concentrate, with the inventory service as the single origin. If a regional Redis fails, the API falls back to inventory with a circuit breaker and reduced concurrency, and returns stale schedule data from CDN in the meantime. Schedules keep working during an availability outage, which is the right degradation order.
What I would measure
Cache hit ratio per route and cabin, p99 origin latency on miss, event lag from inventory to cache delete, and the rate of hold failures caused by stale availability. If event lag exceeds the TTL, the TTL is not the problem. The consumer is behind, and I would scale it before tuning anything else.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Design a real-time flight status update system for Amadeus handling millions of flights with low latency?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
I would split this into ingestion, a canonical flight state, and fan-out, because the hard problems are different in each. Ingestion normalises conflicting airline and airport feeds into one event stream. The state store resolves out-of-order and duplicate events into the current status for a flight. Fan-out pushes only the delta to whoever asked for that flight, instead of making every app poll a database.
Assume 120,000 commercial flights per day globally, about 8 status changes per flight on average (scheduled, gate, boarding, departed, landed, plus delays and diversions), so roughly 1 million updates per day. That is only about 12 per second on average, but peaks are not average. A hub disruption or a weather event can concentrate updates from thousands of flights into minutes, and fan-out multiplies each update by its subscribers. I would design for 2,000 events per second sustained ingestion and 50,000 concurrent push connections, with a p99 budget of under 2 seconds from source event to subscriber notification. Those are design targets for this exercise, not Amadeus published figures.
Ingestion and normalisation
Sources disagree. An airline says a flight departed at 14:03, the airport AODB says 14:07, and ADS-B shows wheels-up at 14:05. I would not pick a winner at ingest time. Every source event keeps its source, source timestamp, ingestion timestamp, and a source sequence number where available. The normaliser maps airline-specific codes into a canonical model: flight_id (carrier plus flight number plus operating date), status, scheduled_time, estimated_time, gate, terminal, and version.
Partitioning matters for ordering. Kafka topics are partitioned by hash of flight_id, so all events for one flight land on the same partition and are processed in order by one consumer group. That gives per-flight ordering without a global lock. Cross-flight ordering is not needed.
State store and conflict resolution
The state store holds one row per flight instance, not per flight number, because the same flight number operates daily. A write is accepted only if its version is newer than the stored version, or if the source timestamp is newer and the version is equal. This makes replays and retries safe.
# Python 3.11, consumer logic checked against this shape
def apply_event(store, event):
current = store.get(event.flight_id)
if current and event.version < current.version:
return "stale" # duplicate or out-of-order replay
if current and event.version == current.version and event.source_ts <= current.source_ts:
return "duplicate"
store.upsert(event.flight_id, event)
publish_delta(event.flight_id, event) # only on accepted change
return "applied"A worked trace for one flight, AF006 2026-05-12:
| Time (UTC) | Source | Event | Version | Result |
|---|---|---|---|---|
| 14:03:10 | Airline API | departed, actual 14:03 | 41 | applied, delta published |
| 14:03:12 | Airline API retry | departed, actual 14:03 | 41 | duplicate, dropped |
| 14:03:09 | Airport AODB (late) | departed, actual 14:07 | 40 | stale, dropped |
| 14:05:00 | ADS-B | airborne | 42 | applied, delta published |
Without the version check, the late AODB message would flip a departed flight back in time and trigger a second wave of notifications to every subscriber.
Fan-out: push first, poll as fallback
Subscribers are airlines, airports, travel agencies, and consumer apps. They do not all want the same thing. An airport operations screen needs every flight at a terminal. A travel agency needs only flights its passengers are on. A mobile app needs one flight.
I would run a push gateway holding WebSocket or Server-Sent Events connections, sharded by subscription key. A subscription is a set of flight IDs or a filter such as airport = CDG and status in (delayed, cancelled). On a delta, the gateway looks up subscribers for that flight ID in Redis, then writes only to those sockets. Polling clients get GET /flights/{id} backed by a CDN or Redis cache with a 5 to 10 second TTL, plus an ETag from the version, so a poller can send If-None-Match and get a 304.
| Approach | Latency | Load on server | When I would use it |
|---|---|---|---|
| WebSocket push | under 1 s typical | one connection per active subscriber | live boards, ops screens, apps in foreground |
| SSE push | similar, simpler reconnect | same, text only | one-way status feeds, easier scaling |
| Poll with ETag and cache | 5 to 10 s stale | request per poller per interval | travel agency backends, low update rate |
Push fails in predictable ways. A slow client socket blocks its shard, so each connection gets a bounded outbound queue and is dropped after a timeout, then reconnects and resyncs from the state store. A reconnecting client asks for since_version, and the gateway replays deltas from a short retention buffer (for example 15 minutes in Kafka) before going live. That closes the gap between disconnect and reconnect without a full snapshot.
Failure modes I would name in the interview
Source outage: if an airline feed stops, flights from that carrier go stale. I would expose last_source_ts per carrier and alert when it lags more than 5 minutes, and mark affected flights as data_stale rather than silently showing old times. Conflicting sources: keep both timestamps in the audit log, display the canonical one, and let the airline of record override for its own flights. Hot partitions: a single hub closure can make one airport dominate traffic, so partition count and consumer parallelism are sized for peak hub traffic, not daily average. Backpressure: if the state store slows, consumers lag, and I would shed non-critical enrichment (for example weather lookups) before shedding status deltas.
For Amadeus specifically, the integration surface is the product. Airlines connect through existing GDS and departure control feeds, airports through AODB interfaces, and agencies through the same APIs that serve schedules. Keeping the canonical model stable while adapters change per source is what lets a new airline or airport be added without touching the fan-out layer.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Given a list of flight bookings, each with a departure and arrival airport code and a timestamp, write a function to find the longest layover duration for any given flight itinerary?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
I would clarify two things first: the list is the segments of one itinerary, and the timestamps are comparable instants, ideally epoch seconds in UTC. If they are local wall-clock times at different airports, I convert them before doing any arithmetic. Then I sort by departure, check that each arrival airport matches the next departure airport, and take the maximum of next.departure - previous.arrival.
from dataclasses import dataclass
@dataclass(frozen=True)
class Booking:
dep: str # e.g. "JFK"
arr: str # e.g. "LHR"
dep_ts: int # epoch seconds, UTC
arr_ts: int # epoch seconds, UTC
def longest_layover(bookings: list[Booking]) -> int:
"""Return the longest layover in seconds. 0 if fewer than 2 segments."""
if len(bookings) < 2:
return 0
ordered = sorted(bookings, key=lambda b: b.dep_ts)
longest = 0
for prev, nxt in zip(ordered, ordered[1:]):
if prev.arr != nxt.dep:
raise ValueError(f"Broken itinerary: {prev.arr} != {nxt.dep}")
layover = nxt.dep_ts - prev.arr_ts
if layover < 0:
raise ValueError("Negative layover: next flight departs before previous arrives")
longest = max(longest, layover)
return longestSorting is O(n log n) and the scan is O(n), so sorting dominates. For a single itinerary n is small, usually under 10, and the sort is cheap insurance against bookings arriving out of order from a PNR feed or a shuffled API response.
Worked trace
Input, deliberately shuffled:
| Segment | Dep | Arr | Departs (UTC) | Arrives (UTC) |
|---|---|---|---|---|
| 1 | JFK | LHR | 08:00 | 20:00 |
| 2 | LHR | FRA | 23:30 | 02:00 next day |
| 3 | FRA | BOM | 06:00 next day | 17:30 next day |
After sorting by departure, the scan computes:
| Pair | Layover calculation | Layover |
|---|---|---|
| JFK-LHR to LHR-FRA | 23:30 - 20:00 | 3 h 30 min |
| LHR-FRA to FRA-BOM | 06:00 - 02:00 | 4 h 00 min |
The function returns 14,400 seconds (4 hours). Note the overnight arrival: epoch arithmetic handles it without special cases, whereas subtracting local clock times would give a negative or wrong result.
Where this breaks in practice
| Failure mode | Symptom | Handling |
|---|---|---|
| Missing segment | prev.arr != nxt.dep, e.g. LHR followed by CDG | Raise and let the caller decide. Silently skipping would report a layover across a gap that is not a connection. |
| Overlapping or mis-timed data | Negative layover | Raise. A negative value usually means a schedule change was applied to one segment but not the next, common in Amadeus PNR updates. |
| Duplicate segment | Two identical bookings, layover of 0 or negative | Deduplicate by flight number plus departure time upstream, or the duplicate will corrupt the chain check. |
| Local times with DST | Layover off by an hour around a clock change | Store and compare UTC instants only. Airport-local time is for display. |
| Single segment or empty list | No layover exists | Return 0, and document that 0 means "no connection" rather than a zero-minute connection. |
If the input were bookings for many passengers mixed together, I would group by itinerary or PNR reference first and run this per group. The core scan does not change. I would also return the layover as a timedelta in production code for readability, converting to seconds only at the boundary if the caller needs a number.
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 function to find the shortest path between two airports on a flight network graph, considering flight durations and potential layover times?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
Model airports as nodes and flights as directed edges. If each edge has a fixed cost, duration + layover, this is a shortest path problem with non-negative weights, so Dijkstra with a binary heap gives the optimum in O((V + E) log V). I would clarify one thing first: is the layover a fixed number per connection, or does it depend on when you arrive? That decides whether weights are static or time-dependent, and it is the point interviewers probe.
Assume UTC times, waiting is allowed, and the network satisfies the FIFO property: leaving later cannot get you there earlier. Under FIFO, a time-dependent version of Dijkstra that always expands the earliest-arrival airport still works, because the earliest arrival at an intermediate airport can never lead to a worse arrival downstream.
import heapq
def shortest_path(graph, start, goal):
# graph[u] = [(v, duration_min + layover_min), ...]
dist = {start: 0}
prev = {}
pq = [(0, start)]
while pq:
d, u = heapq.heappop(pq)
if d != dist.get(u):
continue # stale heap entry
if u == goal:
break
for v, w in graph.get(u, []):
nd = d + w
if nd < dist.get(v, float('inf')):
dist[v] = nd
prev[v] = u
heapq.heappush(pq, (nd, v))
if goal not in dist:
return None, float('inf')
path, node = [], goal
while node != start:
path.append(node)
node = prev[node]
path.append(start)
return path[::-1], dist[goal]Worked trace on a small network, costs in minutes:
| Step | Popped | Relaxed edges | dist updated |
|---|---|---|---|
| 1 | JFK (0) | JFK-LHR 420, JFK-CDG 430 | LHR 420, CDG 430 |
| 2 | LHR (420) | LHR-FRA 65+45=110 | FRA 530 |
| 3 | CDG (430) | CDG-FRA 70+30=100 | FRA stays 530 (530 < 530 is false) |
| 4 | FRA (530) | FRA-DEL 480+60=540 | DEL 1070 |
Result: JFK to DEL via LHR and FRA, 1070 minutes. The CDG route ties on arrival but does not improve it, which is why the strict < matters for deterministic tie-breaking.
When the static model breaks
Real schedules make the edge cost a function of arrival time. A flight that departs at 09:00 cannot be boarded if you land at 08:50 and the minimum connection time at that airport is 45 minutes. The cost becomes wait + duration, where wait is the gap until the next feasible departure. The fix is to replace the fixed weight with a next_arrival(u, v, t) function and keep the same heap loop, using a timetable sorted by departure time and binary search to find the first departure at or after t + MCT. Complexity stays the same per edge relaxation, plus a log F search over that route's departures.
| Model | Edge cost | Algorithm | When to use it |
|---|---|---|---|
| Fixed layover | duration + layover | Dijkstra | Planning on aggregated route data, no timetable |
| Scheduled departures | wait(t) + duration | Time-dependent Dijkstra | Live itinerary search, connection feasibility matters |
| Layover depends on incoming airline | state-dependent | Dijkstra over expanded state | MCT differs by carrier or terminal, so earliest arrival alone is not sufficient state |
That last row is the failure mode people miss. If the minimum connection time depends on which airline you arrived on, two arrivals at the same airport at different times are not comparable by time alone. The state has to become (airport, arriving_airline) or you can discard a slightly later arrival that would have made a tight connection. The same applies across terminals at a large hub.
Failure modes and scale
Disconnected components return no path, so the function returns None rather than raising. Time zones and daylight saving corrupt results if local times are stored, so store and compare in UTC and convert only for display. Overnight connections need the timetable to roll into the next day, otherwise the last flight of the day looks like the end of the network. For a graph with millions of airports and flights, Dijkstra still runs but explores most of it. A* with an admissible heuristic, such as great-circle distance divided by the fastest plausible aircraft speed, prunes the search while keeping optimality, and early exit when the goal is popped is already in the code above. I would not reach for Bellman-Ford here: durations and layovers are never negative, and paying O(VE) buys nothing.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Write a function that takes a price string and validates if it is a plausible price, considering currency formats and invalid characters?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
I would clarify the contract first, because "plausible" is doing a lot of work. I assume the input is a user-facing string from a booking or pricing flow, the output is a boolean plus, in production, a parsed amount and currency, and I need to reject strings that look numeric but would price a ticket wrong. That means I do not accept whatever float() accepts. I define the grammar, parse against it, then apply range and currency rules.
My grammar: optional currency symbol or ISO 4217 code, optional sign only if refunds are in scope, digits with optional thousands separators, optional decimal part, optional currency code at the end. No letters other than a valid currency code, no spaces inside the number, no scientific notation, no NaN or inf, no multiple decimal points. I also need a locale or an explicit format flag, because 1,234 means 1234 in en-US and 1.234 in de-DE. Without that, I reject ambiguous strings rather than guess.
import re
from decimal import Decimal, InvalidOperation
# ISO 4217 minor units for common travel currencies; default 2
MINOR_UNITS = {"JPY": 0, "KRW": 0, "KWD": 3, "BHD": 3}
SYMBOLS = {"$": "USD", "€": "EUR", "£": "GBP", "¥": "JPY"}
MAX_AMOUNT = Decimal("999999999.99")
# en-US style: 1,234.56 or 1234.56 or 1234
_US = re.compile(r"^(?P<sym>[$€£¥])?\s*(?P<num>\d{1,3}(?:,\d{3})*(?:\.\d+)?|\d+(?:\.\d+)?)\s*(?P<code>[A-Z]{3})?$")
def parse_price(s: str, locale: str = "en-US") -> tuple[Decimal, str | None] | None:
if not isinstance(s, str) or not s.strip() or locale != "en-US":
return None # other locales need their own separator rules, not a guess
m = _US.match(s.strip())
if not m:
return None
sym, code = m.group("sym"), m.group("code")
if sym and code and SYMBOLS[sym] != code:
return None # $500 EUR is contradictory, not plausible
currency = code or (SYMBOLS[sym] if sym else None)
num = m.group("num").replace(",", "")
try:
amount = Decimal(num)
except InvalidOperation:
return None
if amount < 0 or amount > MAX_AMOUNT:
return None
if currency:
decimals = len(num.partition(".")[2]) if "." in num else 0
if decimals > MINOR_UNITS.get(currency, 2):
return None # 100.999 USD, or 100.5 JPY, cannot be charged as written
return amount, currency
def is_plausible_price(s: str, locale: str = "en-US") -> bool:
return parse_price(s, locale) is not NoneChecked against Python 3.12. Decimal matters here. float("0.1") + float("0.2") is not 0.3, and a fare total built from floats will drift by cents across a multi-leg itinerary. Parsing to Decimal keeps the string value exact until the payment boundary.
Worked trace:
| Input | Result | Reason |
|---|---|---|
123.45 EUR | Decimal("123.45"), EUR | code suffix, 2 decimals, in range |
$500 | Decimal("500"), USD | symbol prefix, no decimals needed |
99.99 | Decimal("99.99"), None | bare amount, currency resolved later |
1,234.56 | Decimal("1234.56"), None | valid thousands grouping |
12,34.56 | rejected | comma not in a 3-digit group |
1.234,56 EUR | rejected in en-US | European format, needs de-DE rules |
$500 EUR | rejected | symbol and code disagree |
100.999 USD | rejected | exceeds 2 minor units for USD |
100.5 JPY | rejected | JPY has 0 minor units |
1e3, NaN, inf, --5, 5..00, abc | rejected | not in the grammar, even though float() accepts some |
-20.00 | rejected | negative only if the caller opts into refunds |
Two design choices an interviewer will push on. First, regex alone versus parse then validate. A single regex can check shape, but it cannot check MAX_AMOUNT, minor units per currency, or symbol and code agreement without becoming unreadable. I keep the regex for shape and do the semantic checks in code, which is where the travel-specific rules live. Second, boolean versus structured result. The question asks for validation, so the boolean is the interface, but returning (amount, currency) from the same parse avoids a second parse downstream and a time-of-check to time-of-use gap where the validated string is re-parsed differently.
Failure modes I would name: locale ambiguity on 1,234, which I reject unless the caller supplies a locale; currency symbols that map to more than one currency, such as $ for USD, CAD, AUD or ¥ for JPY and CNY, which is why I prefer an explicit code when the amount will be charged; and amounts with excess precision, which I reject rather than round, because silently rounding 99.999 to 100.00 changes the fare the customer saw. If the product wants rounding, that is a separate, explicit step with a stated rounding mode, not something validation does by accident.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Tell me about a time you encountered a significant technical challenge or bug in a production system that you were responsible for?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
I owned the offer-pricing path in a flight search service serving travel agencies. After a deploy, our reconciliation job flagged that about 340 bookings in six hours had been priced in the wrong currency. The cache key for cached offers did not include currency, so a EUR offer cached for one agency was served to a USD agency. I rolled back the deploy, purged the affected cache keys, re-priced the bookings from the source of truth, and owned the refund and reissue workflow with Finance. The fix was a one-line cache key change plus a contract test that would have caught it before deploy.
What happened
The service cached search(origin, destination, date, cabin) for 60 seconds to absorb repeated agency polling. Currency was resolved downstream from the agency profile, after the cache lookup. That ordering was fine when every caller in a region used the same currency. It broke when we onboarded a second agency group in the same region using a different settlement currency.
| Time (UTC) | Event |
|---|---|
| 09:12 | Deploy adds multi-currency agency support. Cache lookup unchanged. |
| 09:40 | First USD agency queries a route previously cached in EUR. |
| 10:05 | Reconciliation compares booked fare currency against agency profile. 47 mismatches. |
| 10:20 | I page the on-call, confirm cache key in code and in Redis keys. |
| 10:35 | Rollback of the deploy, targeted purge of offer keys for affected routes. |
| 11:00 | Pricing re-run from the GDS source for the 340 bookings. 212 undercharged, 128 overcharged. |
| 14:00 | Refund and reissue runbook executed with Finance sign-off. No agency had to raise a ticket. |
Detection mattered more than the fix. The reconciliation job already existed for fare drift, but it ran hourly and only alerted above a threshold. I lowered the threshold for currency mismatch to any occurrence, because a single wrong-currency booking is never noise.
Root cause, in code
Before:
// Java 17, offer cache in the search service
String key = "offer:" + origin + ":" + dest + ":" + date + ":" + cabin;
Offer offer = cache.get(key);
if (offer == null) {
offer = pricingService.price(origin, dest, date, cabin, agency.getCurrency());
cache.put(key, offer, Duration.ofSeconds(60));
}
return offer; // currency taken from whichever agency filled the cacheAfter:
String key = "offer:" + origin + ":" + dest + ":" + date + ":" + cabin
+ ":" + agency.getCurrency() + ":" + agency.getFareBrand();
Offer offer = cache.get(key);
if (offer == null) {
offer = pricingService.price(origin, dest, date, cabin, agency.getCurrency());
cache.put(key, offer, Duration.ofSeconds(60));
}
return offer;The deeper failure was a missing contract test. The pricing service test asserted the returned currency matched the request, but the cache layer test used a single fake agency. A test with two agencies, same route, different currencies, would have failed on the old code in milliseconds.
What I changed afterwards
I added the two-agency cache test, a dashboard panel for currency mismatch count with a zero-tolerance alert, and a deploy checklist item that any change to a cache key requires a version bump or a full purge, because old keys otherwise linger until TTL expiry. I also moved currency resolution before the cache lookup, so future fields added to the key are harder to forget.
If an interviewer pushes on why I did not just fix forward, the answer is blast radius. The rollback took four minutes and stopped new bad bookings. The code fix needed the contract test and a cache purge, which I wanted to do deliberately rather than under pressure. Owning the incident meant owning the customer remediation too, not just the patch.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8What interests you about working on software solutions for the travel industry, and how do your skills align with the challenges in this domain?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
I like travel because the hard parts are not abstract. Inventory is shared, time sensitive and sold through many channels at once, and a mistake shows up as a passenger who cannot board. That forces clear thinking about consistency, freshness and failure, which is the kind of problem I enjoy.
My experience is mostly in backend services that had to stay correct under retries and spikes. That maps well here. I have built order flows where a client retry must not create a second order, and I have sized services from measured latency instead of averages. I have not worked inside a GDS or a passenger service system, so the domain rules around fares, interline and disruption handling are things I would need to learn from the people who own them.
A judgement call I keep thinking about
The trade off I find interesting is freshness against availability during irregular operations. If a flight cancels, search and booking caches can keep offering seats that no longer exist. Serving a slightly slower answer on the booking path is cheaper than an oversell that becomes a denied boarding and a rebooking cost. On exploratory search I would accept a short cache life, maybe 30 to 60 seconds, and show the client when that data was refreshed. On the path that holds inventory I would check the source of truth and hold with an expiry.
That is where I would put my time first. A hold that expires in, say, 10 minutes, an idempotency key on the create call, and a version check on confirm. If two agents try to confirm the last seat, one wins and the other gets a clear conflict it can act on, rather than both believing they succeeded.
I also think about peak shape. Holiday and disruption peaks are not random. They follow schedules and weather. When I size a service I start with Little's Law. If, hypothetically, we get 3,000 requests a second at 120 ms median latency, that is about 360 requests in flight at once. A pool of 50 connections per instance will queue well before the CPU looks busy, so I would scale out or raise the pool and retest under that shape, and shed low priority search before checkout starves.
# Python 3.12, illustrative hold logic
def confirm_hold(hold, expected_version):
if hold.version != expected_version:
return {"status": 409, "code": "hold_changed"}
if hold.expires_at < now():
return {"status": 410, "code": "hold_expired"}
hold.status = "confirmed"
hold.version += 1
return {"status": 200, "hold": hold}The point of that snippet is the order of checks. Version first, expiry second, state change last, so a retry after a timeout does not confirm a hold that has already been taken by someone else.
What I would probe in the loop
I would ask how your teams draw the line between the legacy core and newer offer and order services, how fare rules are evaluated when pricing has to stay fast, and how availability is invalidated when operations change a schedule. Those answers would tell me more about the real constraints than any generic architecture diagram.
That mix, a domain where correctness has a visible cost, and engineering where I can measure whether a change helped, is why I want to work on this problem.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9How would you evaluate whether a decision tree is the right model and assess its performance before and after deployment?
Reported in Amadeus It Group Software Engineer Interview Guide
The 90-second answer
I would start by asking what decision the tree drives and what a wrong prediction costs. At Amadeus that matters because a model predicting booking cancellation, no-show, or refund behaviour feeds inventory and revenue systems, so a false positive can release seats that sell, while a false negative leaves empty seats. If the cost is asymmetric, accuracy alone tells me nothing.
Then I check whether a tree fits the data and the use case. Trees handle mixed categorical and numeric features, non-linear thresholds, and missing values without much preprocessing, and a shallow tree is auditable by a business user. That is a real advantage when an airline or agency asks why a booking was flagged. The weakness is instability: a small change in training data can produce a different tree, and axis-aligned splits waste depth on smooth relationships. If I need calibrated probabilities, extrapolation, or the best raw score, I would benchmark logistic regression and a gradient-boosted ensemble against the tree and only keep the tree if it is close enough that interpretability wins.
Pre-deployment evaluation
Take cancellation prediction as the concrete case. Features available at scoring time might be days to departure, fare refundability, booking channel, payment method, and party size. I would exclude anything known only after the outcome, such as refund issued or a later rebooking, because that leaks the label.
I split by time, not randomly, since travel data drifts with season and schedule changes. Train on earlier months, validate on the next month, test on a later month held out until the end. Inside training I use stratified cross-validation to tune depth and min_samples_leaf, with cost-complexity pruning to keep the tree small.
# Python 3.11, scikit-learn 1.5. Checked against the documented API.
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.metrics import confusion_matrix, precision_recall_curve
clf = DecisionTreeClassifier(
max_depth=5,
min_samples_leaf=200,
ccp_alpha=0.001, # pruning strength, tuned on validation data
class_weight="balanced",
random_state=42,
)
proba = cross_val_predict(
clf, X_train, y_train,
cv=StratifiedKFold(5, shuffle=True, random_state=42),
method="predict_proba",
)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_train, proba)I pick the threshold from the precision-recall curve using the business cost, not 0.5 by default. Suppose, as a labelled hypothetical, the test set has 10,000 bookings and 8% cancel. At the chosen threshold the confusion matrix is:
| Predicted cancel | Predicted keep | |
|---|---|---|
| Actually cancels (800) | 560 | 240 |
| Actually keeps (9,200) | 460 | 8,740 |
That gives recall 70% and precision about 55%. Whether that is acceptable depends on the cost ratio. If releasing a seat that would have flown costs five times a missed cancellation, I move the threshold up and accept lower recall. I also check calibration in bins, performance per market and channel, and stability of the top splits across folds. A tree whose root split flips between folds is not ready, however good the headline score looks.
| Candidate | Strength here | When I would drop the tree |
|---|---|---|
| Decision tree, depth 5 | Auditable rules, handles thresholds | Unstable splits, poor probability estimates |
| Logistic regression | Calibrated, stable, smooth effects | Misses sharp fare or time thresholds |
| Gradient boosting | Usually best ranking score | Harder to explain to a non-technical owner |
After deployment
I would ship in shadow mode first, scoring live bookings without acting on the output, and compare predicted against realised cancellations once labels mature. Cancellation labels arrive late, days or weeks after scoring, so I track leading indicators in the meantime: score distribution, share flagged, and feature drift using population stability index per feature. A PSI above 0.25 on days-to-departure usually means a schedule or sales mix change, not a broken model.
Once labels mature I recompute precision and recall on the same threshold, sliced by market and channel, and compare against the pre-deployment test figures. I also watch for feedback effects: if flagged bookings get extra scrutiny or different treatment, their outcomes change and the model starts grading its own intervention. Retraining is triggered by a sustained drop in recall or calibration error, not by a calendar alone, and every retrain repeats the temporal split and the leakage check. The previous model stays deployable so a rollback is a config change, not a rebuild.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Design a BookMyShow-style app and defend the data structure and database choices?
Reported in Amadeus It Group Software Engineer Interview Guide
The 90-second answer
I would split the problem into catalogue, inventory, and booking, because they have different access patterns. Catalogue (movies, cinemas, shows) is read-heavy and changes rarely. Inventory (which seats are free for a specific show) is write-heavy, contended, and must never oversell. Booking is a short transaction that moves seats from held to sold.
For a single-region launch I would use PostgreSQL as the system of record, Redis for the seat hold and the live seat map cache, and an in-memory structure in the booking service for fast availability checks. I would not start with a distributed database or a separate inventory service. The hard part is not storing rows. It is preventing two users from buying the same seat.
Data model
-- PostgreSQL 16, checked against current docs
CREATE TABLE shows (
show_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
movie_id BIGINT NOT NULL,
screen_id BIGINT NOT NULL,
starts_at TIMESTAMPTZ NOT NULL,
format TEXT NOT NULL -- 2D, IMAX, etc.
);
CREATE TABLE seats (
seat_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
screen_id BIGINT NOT NULL,
row_label TEXT NOT NULL,
seat_no INT NOT NULL,
tier TEXT NOT NULL, -- standard, premium, recliner
UNIQUE (screen_id, row_label, seat_no)
);
CREATE TABLE seat_inventory (
show_id BIGINT NOT NULL REFERENCES shows(show_id),
seat_id BIGINT NOT NULL REFERENCES seats(seat_id),
status TEXT NOT NULL, -- available, held, sold
hold_id UUID,
expires_at TIMESTAMPTZ,
PRIMARY KEY (show_id, seat_id)
);
CREATE INDEX ON seat_inventory (show_id, status) WHERE status = 'available';
CREATE TABLE bookings (
booking_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL,
show_id BIGINT NOT NULL,
status TEXT NOT NULL, -- pending_payment, confirmed, cancelled, expired
total_paise BIGINT NOT NULL,
idempotency_key TEXT UNIQUE NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE booking_seats (
booking_id BIGINT NOT NULL REFERENCES bookings(booking_id),
seat_id BIGINT NOT NULL,
price_paise BIGINT NOT NULL,
PRIMARY KEY (booking_id, seat_id)
);seat_inventory is the row that decides truth. One row per seat per show keeps the count honest and makes a sold-out show a simple COUNT. For a 300-seat screen and 40 shows a day, that is 12,000 rows per screen per day, which PostgreSQL handles without partitioning. I would partition seat_inventory by month only when a chain passes roughly 100 million rows, because partition pruning then matters for expiry sweeps.
Data structures in the service
The seat map for one show is a bitmap. With 300 seats it fits in five 64-bit words. A bit set means unavailable. That gives O(1) check and set, and a whole screen can be sent to the client as a compact array. I would keep the bitmap in Redis as a hash per show, rebuilt from PostgreSQL on a cache miss, and never treat Redis as the record of a sale.
For finding adjacent seats for a group, I would keep seats grouped by row in a sorted list of seat numbers. A request for four together scans one row, not the whole screen. An interval tree is overkill here. Seats are fixed positions, not arbitrary time ranges, so a per-row sorted list plus the bitmap is simpler and fast enough.
Holds need expiry. I would store holds in Redis with a TTL of 10 minutes (a product choice, labelled as an assumption) and also write expires_at in PostgreSQL. Redis tells the service what to release quickly. PostgreSQL is what a recovery job uses after a crash.
The booking flow and the race
The conditional update is the defence against oversell:
UPDATE seat_inventory
SET status = 'held', hold_id = $1, expires_at = now() + interval '10 minutes'
WHERE show_id = $2 AND seat_id = ANY($3) AND status = 'available';
-- Check affected row count in the application. It must equal the number of seats requested.Worked trace, two users, one seat left in row C:
| Time | User A | User B | Result |
|---|---|---|---|
| t+0 ms | UPDATE ... WHERE status='available' | 1 row updated, seat held for A | |
| t+5 ms | same UPDATE | 0 rows updated, B gets 409 seat_unavailable | |
| t+10 min | no payment | Expiry job sets seat back to available, Redis hold deleted |
If the row count is short, the transaction rolls back and any Redis hold is released. That check matters more than the lock. A SELECT ... FOR UPDATE on the show row would also work, but it serialises every hold for that show. The conditional update only contends on the rows being bought.
Why PostgreSQL, and what I would not pick
| Store | Fit here | Where it fails |
|---|---|---|
| PostgreSQL | ACID booking transaction, joins across shows, seats, payments, easy conditional updates | Seat map reads at very high fan-out need a cache in front |
| Redis | Bitmap, TTL holds, session and rate limits, sub-millisecond reads | Data loss on eviction or failover, so never the only copy of a sale |
| MongoDB | Flexible catalogue documents | Booking needs multi-row atomicity across inventory and payment state, which is awkward to reason about |
| Cassandra | Huge write volume across regions | No cheap conditional multi-row transaction for "hold these 4 seats or none" |
At Amadeus scale I would expect the same pattern to be questioned for flights, where inventory is shared across channels. The answer there is the same shape: one authoritative inventory row per sellable unit, conditional updates, and idempotency keys on every create so a retried payment callback cannot confirm a booking twice.
Failure modes I would name in the interview
Payment succeeds but the callback is lost. The booking stays pending_payment with seats held. A reconciliation job queries the payment gateway by idempotency_key and either confirms or releases the hold. Without that job, seats leak until expiry and revenue is lost.
Redis fails over and loses a hold. The PostgreSQL row still says held with expires_at, so the seat is not sold to someone else. The user may see a stale map for a few seconds. That is acceptable. Selling the same seat twice is not.
Clock skew across app servers. I would compare expires_at only in the database, using now() there, and never trust a client-supplied expiry time.
A show sells out during peak. The seat_inventory (show_id, status) partial index keeps the availability query cheap, and the seat map cache absorbs repeated reads. If p99 on holds still climbs past a few hundred milliseconds in load tests, the next step is sharding holds by show_id across booking service instances, not moving the source of truth out of PostgreSQL.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11What architectures have you implemented and why did you use them?
Reported in System Design Architecture Choices
The 90-second answer
I pick architecture from the constraint that will hurt first: consistency, availability, or change rate. In travel systems that usually means three patterns I have shipped. A modular monolith for booking and PNR logic where invariants span several aggregates. Event-driven services around it for inventory, pricing and notifications where scale and failure isolation matter more than a single transaction. And a read-optimised layer in front of both, because agencies hammer the same schedules and availability queries all day.
I would not start with microservices for a new booking flow. Splitting create PNR, hold inventory, price, and ticket into separate deployables on day one turns one ACID transaction into a distributed saga you have to debug at 2 a.m. during peak season. I start modular, extract a service only when I can name the scaling or team boundary that forces it.
What I actually built
First, a booking core as a modular monolith in Java 17 with Spring Boot. Modules were pnr, inventory, pricing, payment, each with its own package and database tables, but one deployable and one transaction boundary for the create-PNR use case. Inside, I used hexagonal ports for external GDS and airline APIs so the core did not depend on a vendor SDK. That let us run the same logic against a test airline and a production carrier by swapping an adapter.
Second, flight status and schedule ingestion as event-driven services. Airlines and internal feeds publish ScheduleChanged and StatusChanged events to Kafka. Consumers update a materialised view in Postgres and invalidate a Redis cache. Producers use the transactional outbox, because publishing to Kafka and writing the database in the same request otherwise loses events on a crash between the two writes.
// Java 17, transactional outbox relay (simplified)
@Transactional
public void publishStatusChange(FlightStatus s) {
flightStatusRepo.save(s);
outboxRepo.save(new OutboxEvent(
s.flightId(), "FlightStatusChanged", toJson(s)));
}
@Scheduled(fixedDelay = 500)
public void relay() {
for (OutboxEvent e : outboxRepo.findTop100ByPublishedFalse()) {
kafka.send(e.topic(), e.key(), e.payload());
e.markPublished();
}
}Consumers are idempotent on (flightId, eventVersion). A redelivery after a rebalance replays the same version and is a no-op, which matters because Kafka gives at-least-once delivery.
Third, a read layer for agency search. Writes go to Postgres as the source of truth. A separate indexer builds denormalised search documents and warms Redis for the top routes. Search never joins five operational tables at request time. At our peak, that moved p99 search latency from about 900 ms on direct joins to under 120 ms, and it let us scale reads without scaling the booking database.
| Pattern | When I used it | What it cost me |
|---|---|---|
| Modular monolith | PNR creation, ticketing, payment invariants | One deploy, larger blast radius if a module leaks |
| Event-driven services | Schedule ingestion, status updates, notifications | Event schema versioning, ordering per key only |
| CQRS-style read model | Agency search and availability | Stale reads by seconds, rebuild pipeline |
| Hexagonal adapters | Airline and GDS integrations | More interfaces to maintain |
Trade-offs and failure modes I watch
The monolith fails when a pricing bug blocks a deployment for inventory. I detect that by module-level metrics and by keeping module boundaries enforced with ArchUnit tests, so extraction later is mechanical. The event pipeline fails silently when a consumer lags. I alert on consumer lag per topic partition and on the age of the newest applied eventVersion per flight, not just on broker health. The read model fails when an indexer falls behind and agencies see sold-out inventory as available. I guard that with a freshness timestamp in the search response and a circuit breaker that falls back to a direct inventory check for the top 1% of routes when lag exceeds 30 seconds.
If I had to rebuild it, I would keep the same split. Booking needs strong consistency in one place. Everything that reacts to change, scales independently, or serves reads at agency volume belongs outside that transaction.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Design a scalable notification service for Amadeus's customer-facing application?
Reported in AmadeusSenior Software Engineer / SDE 3
The 90-second answer
I would separate accepting a notification from delivering it. A synchronous POST /notifications validates the request, checks consent and preferences, writes the request plus an outbox record in one transaction, and returns 202 Accepted with a notification ID. Delivery happens asynchronously, so a slow email or SMS provider never blocks booking, payment, or check-in flows.
Assumptions I would state up front: channels are email, SMS, and push, with in-app as a record of what was sent. Volume is driven by bookings and flight events. A hypothetical peak for a large travel platform might be 30 million notifications a day, averaging about 350 per second and peaking near 3,000 per second during mass disruption or a sale. That peak, plus the cost difference between channels, drives the design more than the average.
Ingest and deduplication. Every producer supplies an Idempotency-Key, typically the source event ID such as booking_confirmed:bkg_8841. The API stores key -> notification_id for 7 days. A retry returns the original 202 and ID instead of creating a second notification. The outbox relay publishes to the queue only after the database commit, which prevents a queued message for a notification that was rolled back.
# Python 3.12, ingest handler sketch
def create_notification(req):
with db.transaction():
seen = db.find_by_idempotency_key(req.idempotency_key)
if seen:
return 202, seen.notification_id # replay, do not requeue
n = db.insert_notification(
id=uuid4(), event=req.event, traveller_id=req.traveller_id,
channel=req.channel, payload=req.payload,
status="PENDING", priority=req.priority)
db.insert_outbox(notification_id=n.id, topic="notify.send")
return 202, n.idRouting, consent, and priority. Workers render from versioned templates keyed by (event, channel, locale). Before sending, the router rechecks consent and channel preferences at send time, because a traveller can opt out while the message sits in the queue. Urgent operational messages, such as a gate change or cancellation, use a separate high-priority lane with its own queue and provider quota. Marketing messages use a low-priority lane and can be delayed or dropped under load.
| Lane | Examples | Delivery target | If provider is down |
|---|---|---|---|
| P0 operational | flight disruption, gate change, payment failure | 99% within 60 s | fail over to second provider, page on-call after 5 min |
| P1 transactional | booking confirmation, receipt, check-in reminder | 99% within 5 min | retry with backoff for 24 h |
| P2 marketing | fare alert, upsell | best effort, same day | drop after expiry, log suppression |
Failure modes I would name in the interview.
Provider outage: each channel has two providers behind a circuit breaker. The router tracks success rate over a rolling 1 minute window and shifts traffic when it falls below 95%. SMS gets special care because cost and carrier filtering differ by country, so routing is per destination country code.
Duplicate sends: the queue delivers at least once, so workers must be idempotent. The send step records provider_message_id before marking SENT, and a redelivered job checks that field first. Without this, a worker crash after the provider accepted the message produces a second SMS.
Missing locale or template: if fr-CA is absent for a new event, the worker falls back to the default locale for that market and raises a metric. It never blocks the queue waiting for a translation.
Bounces and complaints: webhooks update a suppression list per address and per traveller. A hard bounce on email suppresses that address for transactional mail only after a review threshold, because a single bounce can be a transient mailbox error. Consent revocation suppresses all non-operational channels immediately.
Scaling and observability. Workers scale horizontally on queue depth per lane, with separate autoscaling so a marketing burst cannot starve P0. Partitioning is by traveller_id hash for ordering within a traveller, which matters when a cancellation follows a confirmation. Dashboards track queue age by lane, send latency by provider and country, delivery and bounce rates, and cost per 1,000 messages by channel. An alert on P0 queue age above 60 seconds is more useful than an alert on CPU.
I would close by noting what I would not build first: a general campaign builder or a real-time personalization engine. Those sit on top of the same ingest, consent, and delivery core, and they can wait until transactional delivery is reliable under peak disruption load.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Given an array of request costs, find the longest continuous segment whose total cost is at most a budget B?
Reported in AmadeusSenior Software Engineer / SDE 3
The 90-second answer
Assuming request costs are non-negative, which holds for fees, surcharges and processing charges in a customer-facing system, this is a sliding window problem. Keep a window [left, right] whose sum never exceeds B, expand right one element at a time, and move left forward only while the sum is over budget. Record the window whenever its length beats the best seen so far. That gives O(n) time and O(1) extra space, and it returns the longest segment, not just any valid one.
The non-negative assumption is the whole decision. With negative costs a window that is over budget now could come back under budget later, so shrinking left greedily would discard the answer. I would state that assumption up front and ask whether costs can be zero or negative before committing to the algorithm.
Worked trace
Costs [3, 1, 4, 2, 5, 1, 3], budget B = 7. The longest length is 3, for example [1, 4, 2].
| right | cost | window sum after shrink | window | best length |
|---|---|---|---|---|
| 0 | 3 | 3 | [3] | 1 |
| 1 | 1 | 4 | [3, 1] | 2 |
| 2 | 4 | 8, shrink to 5 | [1, 4] | 2 |
| 3 | 2 | 7 | [1, 4, 2] | 3 |
| 4 | 5 | 12, shrink to 7 | [4, 2, 5] is 11, shrink to [2, 5] | 3 |
| 5 | 1 | 8, shrink to 6 | [5, 1] | 3 |
| 6 | 3 | 9, shrink to 4 | [1, 3] | 3 |
At right = 4 the shrink loop removes 4 then 1, leaving [2, 5] with sum 7. The window is valid again, but its length is only 2, so the best stays 3.
Implementation
def longest_within_budget(costs, budget):
left = 0
window_sum = 0
best_start = 0
best_len = 0
for right, cost in enumerate(costs):
window_sum += cost
while window_sum > budget and left <= right:
window_sum -= costs[left]
left += 1
length = right - left + 1 if window_sum <= budget else 0
if length > best_len:
best_len = length
best_start = left
return costs[best_start:best_start + best_len]Returning the slice copies the answer, which is fine for a small result. If the caller only needs the length or the start index, return those instead and avoid the copy. For a large array, say 10 million costs, that copy is the difference between an O(1) and an O(n) tail.
Edge cases and follow-ups
| Case | Behaviour |
|---|---|
| --- | --- |
| --- | --- |
| --- | --- |
| --- | --- |
| --- | --- |
| empty array | returns [], best length 0 |
single cost above B | window empties, left passes right, length recorded as 0 |
| zero costs | window keeps growing, which is correct because zeros extend the segment for free |
| ties in length | first found wins, since the comparison is strict > |
B negative with non-negative costs | no non-empty window qualifies, returns [] |
If costs can be negative, I would switch to prefix sums. Let P[i] be the sum of the first i costs. A segment (l, r] qualifies when P[r] - P[l] <= B, that is P[l] >= P[r] - B. For each r I need the smallest l whose prefix value clears that threshold. Coordinate-compress the prefix values and keep, per value, the earliest index seen, then query the minimum index among values at or above the threshold with a Fenwick tree or segment tree. That is O(n log n) and handles negatives, at the cost of O(n) extra memory. A brute force O(n^2) check is only worth it for tiny inputs or as a correctness oracle in tests.
One more production detail: if this runs over a stream of requests rather than a stored array, the same two pointers work online with a queue, and the best window so far is a running maximum. The array version is the one to write first, because the streaming version is a mechanical adaptation of it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Describe a situation where your proposed architectural design for handling high volume PNR updates conflicted with existing legacy constraints or team performance standards when integrating a third party GDS provider?
Reported in Amadeus IT Group Software Engineer Interview Questions
The 90-second answer
On a GDS integration I proposed replacing nightly batch PNR sync with an event-driven update path: Kafka topic pnr.updated, idempotent consumers, and optimistic concurrency on a version field. That collided with two hard constraints. The legacy PNR store was a mainframe-backed service behind a synchronous SOAP interface with no version column, and the GDS provider throttled us to 50 updates per minute per record locator and locked a PNR for 30 seconds during any write. My design assumed we could write freely and retry aggressively. In production that would have caused lock contention and duplicate itinerary changes.
I kept the event backbone but moved the conflict resolution to the edge. We added an anti-corruption layer that serialised writes per PNR, coalesced bursts, and translated our version into the provider's sequence check.
What I proposed, and why it broke
PNR updates arrive from agencies, airlines and our own ticketing flow. Volume in the example I will use, labelled hypothetical, was 8,000 updates per minute at peak, with bursts to 20,000 when a carrier reissued schedules. Batch sync every 15 minutes meant agencies saw stale seat and SSR data. My first design consumed pnr.updated events directly, updated our store, then called the GDS synchronously per event.
Two failures showed up in load testing:
| Constraint | Assumption in my design | Reality in test |
|---|---|---|
| Legacy store | Version field for optimistic locking | No version, last writer wins, 30 s PNR lock |
| GDS provider | Unlimited retries on timeout | 50 writes/min per locator, timeout often meant write had landed |
| Team standard | p99 under 200 ms end to end | Synchronous GDS call pushed p99 to 1.8 s under burst |
Retrying a timed-out GDS call created duplicate SSR entries. Two consumers handling events for the same PNR in parallel overwrote each other because neither could detect a stale write.
The revised design
Partitioning by record locator guarantees one active writer per PNR. The coalescer holds updates for 2 seconds and sends only the latest state per field group, which cut GDS calls by about 70% in the burst test. The anti-corruption layer maps our internal model to EDIFACT-style segments the provider accepts and adds a client-generated idempotency key per logical change.
// Java 17, consumer checked against Kafka consumer API 3.7
public void onEvent(PnrUpdated event) {
String key = event.pnrId() + ":" + event.changeId();
if (processedKeys.contains(key)) return; // replay after timeout
sequencer.submit(event.pnrId(), () -> {
gdsClient.update(event.pnrId(), event.payload(), key);
processedKeys.add(key);
});
}If the GDS call times out, we do not retry blindly. We query the provider by idempotency key first. Only when the query returns not found do we resend. That turned duplicate SSRs from 340 in the test run to zero.
Trade-offs I stated to the team
The coalescer adds up to 2 seconds of delay, so we exempt fare and ticketing changes from coalescing and send those immediately. Serialising per PNR means a hot PNR with a schedule change queues behind itself, but that queue is bounded and visible in metrics, unlike silent overwrites. We also accepted eventual consistency with the provider: our store shows pending_gds_sync until reconciliation confirms, and the reconciliation job runs every 5 minutes comparing sequence numbers and replays gaps.
Detection matters here. We alert on three signals: GDS throttle responses above 1% of calls, coalescer queue depth per locator above 100, and reconciliation mismatches older than 10 minutes. Each points to a different fix, throttling, a stuck locator, or a lost event, rather than a generic latency alert.
The lesson I took into the next design review was to validate provider limits and legacy locking behaviour before committing to a concurrency model. The event design was sound, but only after the write path respected the systems it had to live with.
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: