Skip to content
Tech Interview Prep

Real Interview Questions for the Software Engineer at Prosus

New

Interview Q&A

9 questions · Flow follows Relevance until this set has a learning order.

Q&A-1What specifically about Prosus's investment strategy and its focus on growth-stage tech companies excites you as a software engineer?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

What excites me is the stage. Prosus does not fund ideas on a slide deck. It buys into companies that already have product-market fit and then has to scale them across countries, payment rails and regulatory regimes without breaking them. That is a different engineering problem from a seed startup, and it is the one I want.

At seed stage the hard question is whether anyone wants the product. At growth stage the hard questions are: can this marketplace handle 10x traffic in Brazil during a holiday peak, can this payments flow survive a new local wallet, can this recommendation system stay fast when the catalogue grows from 100,000 to 10 million listings. Those are scale, reliability and localisation problems, and they reward engineers who care about data modelling, observability and incremental rollout.

Prosus also gives that work a long horizon. It is a listed holding company, spun out of Naspers in 2019 and listed on Euronext Amsterdam, with a large Tencent stake and a portfolio that includes Delivery Hero, OLX, Stack Overflow and Udemy. A long-term owner can fund platform work that does not ship in a quarter: a shared identity service, a fraud platform, a experimentation system reused across businesses. I would rather build that kind of substrate than rebuild it every funding round.

Why the portfolio shape matters for an engineer

BusinessGrowth-stage problem I would want to work on
Delivery HeroOrder routing and dispatch latency across many cities, peak load, rider and restaurant availability
OLXSearch and ranking over a huge, messy classifieds catalogue, trust and safety, duplicate listings
Tencent / WeChat ecosystemHigh-throughput messaging and payments, strict consistency for money movement
UdemyRecommendation and search for learners, pricing experiments, content ingestion at scale

None of those are single-product silos. The interesting work sits in the middle layer: experimentation, payments, identity, fraud signals, data pipelines. If you build that well once, five businesses get faster.

Product-market fit Prosus growth investment Scale traffic and catalogue Localise payments and compliance Shared platform services Reuse across portfolio

The trade-off I would name in the interview

Growth-stage investing is not greenfield. You inherit a codebase, a data model and customers you cannot afford to break. A change that looks clean in a design doc can fail because a partner business depends on the old field semantics. That means more migration work, more dual-write periods, more careful backfills. I am comfortable with that, but I would ask in the loop how platform teams are funded and how much autonomy a business unit has to diverge from a shared service. If the answer is "everything must be centralised", that slows product teams. If the answer is "nothing is shared", you lose the portfolio advantage.

A concrete example of the work

Take OLX search. A naive index rebuild after a schema change might take hours and leave search stale. At growth stage you design for continuous indexing, shadow indexes and a cutover you can roll back in minutes. You measure p99 search latency, index lag and the share of queries returning zero results, and you canary the new ranking model on 1% of traffic before you trust it. That is the kind of unglamorous, high-leverage engineering Prosus's model creates, and it is why the strategy appeals to me more than a pure early-stage fund would.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2Given a list of user interactions on a Prosus e-commerce platform, design an algorithm to identify the top K most frequently occurring sequential patterns of length 2?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

Clarify the unit first. I assume the input is an ordered stream of events per user session, for example view:A, add_to_cart:A, purchase:A, and a pattern of length 2 means two consecutive events inside the same session. I would not count a pair that crosses a session boundary or a long time gap, because that pair never happened in one journey.

With that assumption the exact algorithm is one pass with a hash map and a bounded heap. Count every adjacent pair, then keep only the K largest counts. That is O(N) to count N events, O(P log K) to extract the top K from P distinct pairs, and O(P) memory for the map. For a platform stream I would then swap the exact map for a bounded counter, which I cover below.

Worked trace

Sessions, already ordered by timestamp:

SessionEventsAdjacent pairs counted
s1view:A, add_to_cart:A, purchase:A(view:A, add_to_cart:A), (add_to_cart:A, purchase:A)
s2view:A, view:B, add_to_cart:B(view:A, view:B), (view:B, add_to_cart:B)
s3view:A, add_to_cart:A(view:A, add_to_cart:A)

Counts after the pass: (view:A, add_to_cart:A)=2, (add_to_cart:A, purchase:A)=1, (view:A, view:B)=1, (view:B, add_to_cart:B)=1. For K=2 the heap returns (view:A, add_to_cart:A)=2 and one of the three count-1 pairs. That tie is not an implementation detail. I would state the tie-break in the contract, for example lexicographic order on the pair, or return all pairs tied at the Kth count and let the caller decide.

Code, checked against Python 3.12

Python
import heapq
from collections import Counter

def top_k_pairs(sessions, k):
    counts = Counter()
    for events in sessions:
        for prev, curr in zip(events, events[1:]):
            counts[(prev, curr)] += 1
    if k <= 0:
        return []
    # heapq.nsmallest with a negated count keeps a min-heap of size k
    return heapq.nsmallest(k, counts.items(), key=lambda item: (-item[1], item[0]))

zip(events, events[1:]) is the whole sequential idea. It emits exactly len(events)-1 pairs per session and never joins the last event of one session to the first of the next.

Scaling it on a Prosus-scale stream

The exact map grows with distinct pairs. With 50 million events a day and, say, 200 event types, the pair space is bounded at 40,000, so the map is fine. If events carry product IDs, as in view:product_918273, the pair space explodes and the map becomes the problem. Two options, chosen by whether exactness matters:

ApproachMemoryGuaranteeWhen I use it
Exact CounterO(P) distinct pairsExact countsEvent vocabulary is small or product IDs are bucketed into categories
Space-Saving with m countersO(m), fixedCounts never overestimated, error bounded by N/mProduct-level pairs, streaming, need a hard memory cap
Count-Min SketchO(width x depth), fixedCounts may be overestimated, never underestimatedOnly need approximate ranking and can verify candidates later

Space-Saving is my default for the product-level case. Keep m counters, increment on a hit, and on a miss replace the minimum counter and inherit its count plus one. With m=10,000 and N=50 million, the maximum error on any reported count is at most N/m = 5,000, which I would state next to the result rather than presenting the number as exact.

Failure modes I would name in the interview

Out-of-order events. If events arrive from mobile and web with clock skew, adjacency computed on arrival order is wrong. I would sort by event timestamp inside a session buffer, or bucket by a short window and accept that pairs spanning the bucket edge are missed.

Duplicate delivery. A retried add_to_cart event creates a false (view, add_to_cart) pair. Deduplicate on event ID before counting, in the same pass that builds sessions.

Session definition. A 30 minute inactivity timeout is a choice, not a fact. A pair counted under a 30 minute rule may vanish under a 10 minute rule, so the session rule belongs in the output metadata alongside K and the time window.

Event stream Group by session, sort by timestamp Emit adjacent pairs Count pairs, exact or Space-Saving Min-heap of size K Return top K with tie-break stated

If the interviewer pushes on length 2 specifically, the honest answer is that nothing in the counting step depends on 2. The same pass generalises to length L by counting L-grams, at the cost of a pair space that grows as vocabulary to the power of L, which is exactly why the bounded counter matters more as L grows.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3Design a real-time notification system for Prosus's e-commerce platform for order status, promotions, and new arrivals, considering scalability to millions of users and different notification channels?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

I would split this into event ingestion, a decision layer, and channel delivery, because the three notification types have different urgency and consent rules. Order status is transactional and must arrive in seconds. Promotions and new arrivals are marketing, can be batched, and must respect opt-in and frequency caps. Mixing them in one queue means a flash sale can delay a delivery update.

Order, catalogue and campaign services publish events to Kafka through a transactional outbox, so a database commit and the event cannot diverge. A stateless notification service consumes those events, checks preferences and consent, renders a template, deduplicates on an idempotency key, and routes the message to a priority queue per channel. Push, in-app, email and SMS each sit behind an adapter, so swapping a provider does not touch the routing logic.

For real-time in-app delivery I keep a WebSocket gateway tier in front of Redis. The gateway holds connections and Redis holds a user_id to gateway node mapping, which lets any worker publish to the node that owns the connection. Push via FCM and APNs covers users who are offline. Email and SMS are the fallback path when push fails or the device token is stale.

Order / catalogue / campaign events Kafka via transactional outbox Notification service Preference and consent store Template and dedup service Priority queues Push and WebSocket gateway Email adapter SMS adapter Delivery receipts and retry

Scale, with numbers

Assume, as a worked example, 20 million registered users, 2 million daily active users, and 500,000 order events per day. That is only about 6 order events per second on average, but peaks are spiky: a delivery batch can emit 50,000 events in a minute. Promotions are the real load. One campaign to 5 million users at 10% open rate still means 5 million sends, and providers throttle by sender reputation and per-minute caps.

Partitioning Kafka by user_id keeps all events for one user ordered, which matters when "shipped" must not arrive after "delivered". Workers scale horizontally because they hold no connection state. The WebSocket tier is the stateful part: at 2 million concurrent connections and roughly 50,000 connections per node, I need about 40 gateway nodes, plus headroom for reconnect storms after a deploy. That storm is a concrete failure mode. Clients reconnect with jittered backoff, and the gateway returns a snapshot of missed notifications from Redis rather than replaying the full event log.

Deduplication and ordering

Every event carries a stable key, for example order:42:shipped. Before sending, the worker checks a Redis set with a 48 hour TTL. The check and the insert need to be atomic, otherwise two workers can both pass the check during a rebalance.

Python
# Python 3.12, worker side, Redis 7
key = f"notif:sent:{event.order_id}:{event.type}"
if redis.set(key, "1", nx=True, ex=48 * 3600):
    await channel.send(render(event))
else:
    metrics.incr("notif.duplicate_suppressed")

If the send succeeds but the process dies before writing the receipt, the retry sees the key and skips. That trades a possible duplicate for a possible miss, and for order status I would rather log the ambiguity and reconcile from the order service than silently drop a delivery update.

Channel choice

ChannelTypical latencyCost profileBest for
In-app via WebSocketunder 1 s when onlinelow marginal costorder status for active users
Push (FCM / APNs)1 to 5 slow, provider free tier then per messageorder status, new arrivals for opted-in users
Emailseconds to minuteslow per message at volumeorder receipts, digests
SMSsecondshigh per message, strict carrier limitsdelivery exceptions, OTP, high-value orders only

SMS at scale is where budgets break, so I gate it behind value and failure of cheaper channels. A failed push followed by SMS for a delayed parcel is defensible. SMS for every promotion is not.

Failure modes I would name in the interview

Provider throttling: FCM and email providers return 429 or soft bounces. I would implement per-provider token buckets, exponential backoff with jitter, and a dead-letter queue after three attempts, with an alert on dead-letter depth rather than on raw error rate.

Stale device tokens: push providers return NotRegistered. The adapter must delete the token and mark the user as push-unreachable, otherwise every campaign wastes sends and damages sender reputation.

Consent races: a user opts out while a campaign is mid-flight. The preference check has to happen at send time, not at campaign creation time, and the check needs to be a single read from a replicated store with a short cache TTL, around 60 seconds, so opt-outs propagate quickly.

Template and locale errors: rendering happens in the template service with a fallback to a plain-text version. A missing translation should never block an order status message, so the fallback path is tested in CI with a snapshot per locale.

What I would not build

I would not build a custom push infrastructure or a custom email sending stack. Both are solved problems with reputation, deliverability and compliance attached. I would also not put promotions and order status on the same priority queue, and I would not let the campaign service write directly to channel providers. That coupling is what makes a marketing change become a transactional outage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4Implement a function that takes a total bill amount and a list of participants, each with a potential custom amount already paid, and returns the amounts each remaining participant owes, handling cases where the total paid exceeds the bill?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

I would clarify two things before coding. First, the split is equal unless a participant's custom payment says otherwise. Second, a participant who paid more than their share gets a negative balance, meaning they are owed money, rather than being clamped to zero. Clamping hides the overpayment and the totals stop reconciling.

I would work in integer cents. Floats make 0.1 + 0.2 style errors appear in money, and an interviewer will probe that. The function takes the bill in cents, a list of participants where paid_cents may be missing or None, and returns each participant's remaining balance: share - paid. Positive means they still owe, negative means they should receive a refund.

Python
# Python 3.11
from dataclasses import dataclass

@dataclass
class Participant:
    name: str
    paid_cents: int | None = None  # None means nothing paid yet

def settle(bill_cents: int, participants: list[Participant]) -> list[tuple[str, int]]:
    if bill_cents < 0:
        raise ValueError("bill_cents must be non-negative")
    if not participants:
        raise ValueError("at least one participant is required")
    if len({p.name for p in participants}) != len(participants):
        raise ValueError("duplicate participant names")
    for p in participants:
        if p.paid_cents is not None and p.paid_cents < 0:
            raise ValueError(f"{p.name}: paid_cents cannot be negative")

    n = len(participants)
    base, remainder = divmod(bill_cents, n)
    # First `remainder` participants absorb one extra cent, deterministically.
    shares = [base + (1 if i < remainder else 0) for i in range(n)]

    return [
        (p.name, share - (p.paid_cents or 0))
        for p, share in zip(participants, shares)
    ]

Time is O(n), extra space is O(n) for the shares and result. That is optimal here because every participant must be visited at least once.

Worked trace

Bill of 10000 cents (100.00), three participants. Shares are 3334, 3333, 3333 because divmod(10000, 3) gives remainder 1.

ParticipantPaid (cents)Share (cents)Remaining (cents)Meaning
Ana50003334-1666refund due
BenNone33333333owes 33.33
Cara200033331333owes 13.33

The remaining balances sum to 3000, which equals 10000 - 7000 paid. That invariant is the check I would assert in tests: sum(remaining) == bill_cents - sum(paid).

When total paid exceeds the bill

Suppose the same bill but Ana paid 12000. Her remaining balance is -8666, and the sum of all balances is -2000. I return those negatives and let the caller decide how to refund. Silently raising an exception would make a legitimate overpayment, such as a deposit, impossible to represent. If the product rule is that overpayment is an error, I would add a strict: bool = False parameter and raise ValueError("total paid exceeds bill") only when it is set. The default stays permissive because the arithmetic is still well defined.

Failure modes I would name

Rounding drift: splitting 10000 across 3 people in floats gives 3333.333 each and the last person absorbs the error. Integer cents plus the remainder distribution above keeps the shares summing exactly to the bill.

Missing versus zero payment: paid_cents=None and paid_cents=0 behave the same in the result, but conflating them in input parsing loses the distinction between "not recorded" and "recorded as zero". I keep None through validation and only coerce at the subtraction step.

Duplicate names: returning a dict keyed by name would silently overwrite one participant. I validate uniqueness up front and return a list of tuples so order is preserved and duplicates cannot hide.

Empty input: dividing by zero is the obvious crash. Raising ValueError with a clear message beats returning an empty list that a caller might mistake for "nobody owes anything".

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5Design the backend system for dynamic pricing based on demand and inventory levels, considering frequent price updates and consistency across the platform?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

I would treat price as a derived, versioned fact, not a field I mutate in place. One pricing service owns the calculation for a SKU. It reads demand signals and inventory, writes an immutable price record with a monotonically increasing version, and publishes it. Every read path, product page, search index and checkout, reads that same versioned record. That gives consistency without distributed locks on the hot path.

The split that matters is write path versus read path. Writes are frequent and can be batched and throttled per SKU. Reads are far more frequent and must be cheap, cacheable and tolerant of a few seconds of staleness. Checkout is the exception. It must pin the exact price version the buyer saw, or reprice explicitly and tell the buyer, so we never charge a price nobody agreed to.

Demand events: views, carts, orders Pricing service Inventory service: stock, inbound ETA Price store: versioned records Cache and CDN Search and catalogue index Checkout Order service: pinned price

Core components

The pricing service is the single writer per SKU. Sharding by sku_id hash means two instances never compute a price for the same SKU at once, which removes write conflicts without a global lock. Inside, the function is deliberately boring and auditable:

Python
# Python 3.12, pricing service (simplified)
def compute_price(sku, demand_1h, stock, inbound_in_7d, current_version):
    base = sku.base_price_cents
    # Hypothetical rule for this example: demand pressure moves price up to +/-20%
    pressure = max(-0.20, min(0.20, (demand_1h - sku.demand_baseline) / sku.demand_baseline * 0.10))
    scarcity = 0.15 if stock < sku.reorder_threshold and inbound_in_7d == 0 else 0.0
    new_price = round(base * (1 + pressure + scarcity))
    return PriceRecord(sku_id=sku.id, price_cents=new_price, version=current_version + 1)

Rules live in versioned config, not code deploys, so a bad rule can be rolled back in minutes. Every record stores the inputs that produced it, demand_1h, stock, rule version, so finance can replay why a price moved.

The price store is a key-value store keyed by sku_id holding the latest version, plus an append-only log of all versions. The log feeds the search index and analytics through a change stream. Reads go through a cache layer with a short TTL, 5 to 10 seconds for product pages, and CDN edge caching for anonymous traffic.

Handling frequent updates

Assume, as a worked example, 50,000 active SKUs and a recompute every 30 seconds for the top 10% by traffic. That is 5,000 recomputes per cycle, about 167 writes per second, which is trivial for the store. The problem is not write volume, it is fan-out. If each write invalidates a cached page, we get a thundering herd.

So I do not invalidate on write. I version the cache key: price:{sku_id}:v{version}. The pricing service publishes the new version, the cache fills lazily on the next read, and old entries expire by TTL. Product pages embed the version they rendered with. Search results can lag by a minute because they read from the change stream, and that is acceptable for discovery. Checkout cannot lag.

PathFreshness targetMechanism
Product page10 sVersioned cache key, lazy fill
Search and listing60 sChange stream into index
CartRe-read on viewReads latest version, shows change banner
CheckoutExact version pinnedClient sends price_version, server validates

Consistency at checkout

This is where dynamic pricing systems lose trust. The buyer sees 999, clicks buy, and gets charged 1,099 because a recompute landed in between. My rule: the order is created against a specific price_version. The checkout request carries the version from the page. The server loads that version from the log, checks it is still within a tolerance window, say 5 minutes and 5% price movement, and either accepts it or returns a clear price_changed response with the new price for explicit confirmation. The order record stores price_cents, price_version and the rule version. Refunds and invoices read from the order, never from the current price.

Inventory consistency is separate. Price can be stale by seconds, stock cannot be oversold. The inventory service decrements atomically on order creation and returns available or insufficient_stock. If stock hits zero, it emits an event and the pricing service applies the scarcity rule on the next cycle, typically within 30 seconds. I would not block checkout waiting for a fresh price recompute. I would block on stock, because that is the hard constraint.

Failure modes I would name in the interview

A hot SKU with a flash sale can generate demand events faster than the baseline updates, causing price oscillation. I dampen it with the clamp in the code above and a minimum interval between price changes per SKU, for example 60 seconds, plus a maximum change per cycle. Oscillation shows up as version churn in the log, which is easy to alert on.

A cache stampede after a price change on a homepage hero SKU can send thousands of simultaneous reads to the store. Request coalescing in the cache layer, where concurrent misses for the same key share one upstream fetch, handles that.

If the pricing service falls behind, reads keep serving the last good version and checkout keeps pinning it. That is the right degradation. The alternative, failing checkout because a pricing rule is down, costs more than selling at a slightly stale price for a few minutes. I would alert on recompute lag per shard and on the gap between the latest version timestamp and now.

What I would not do

I would not put pricing logic in the product catalogue service or in the client. Both create two sources of truth and prices that differ between page and checkout. I would not use strong consistency across regions for price reads. A single region writer per SKU with asynchronous replication of the version log is enough, and cross-region synchronous writes would add latency to every price change for a benefit checkout does not need, since checkout pins a version that already exists.

If asked to scale further, the next step is per-market pricing. The same design holds: sku_id becomes (market, sku_id) as the shard key, and the version log gains a market column. Nothing else in the read or checkout path changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6Implement a function to find the median of a data stream that supports adding integers one by one and finding the median efficiently?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

Keep two heaps. A max-heap lo holds the lower half and a min-heap hi holds the upper half. Every element in lo is less than or equal to every element in hi, and lo is either the same size as hi or one larger. Then the median is the top of lo for an odd count, or the average of the two tops for an even count. Both operations are O(log n) for insertion and O(1) for reading the median.

Python
import heapq

class MedianFinder:
    def __init__(self) -> None:
        self.lo = []  # max-heap, stored negated
        self.hi = []  # min-heap

    def add_num(self, x: int) -> None:
        heapq.heappush(self.lo, -x)
        heapq.heappush(self.hi, -heapq.heappop(self.lo))
        if len(self.hi) > len(self.lo):
            heapq.heappush(self.lo, -heapq.heappop(self.hi))

    def find_median(self) -> float:
        if not self.lo:
            raise ValueError("median of empty stream")
        if len(self.lo) > len(self.hi):
            return float(-self.lo[0])
        return (-self.lo[0] + self.hi[0]) / 2.0

Python's heapq is a min-heap, so lo stores negated values to get max-heap behaviour. The push to lo, pop from lo, push to hi sequence puts the new value in the correct half in one pass. The final rebalance restores the size invariant. In Java the same shape uses PriorityQueue with Collections.reverseOrder() for lo.

Worked trace

Inserting 5, 15, 1, 3 in that order:

addlo (max-heap)hi (min-heap)median
5[5][]5.0
15[5][15]10.0
1[5, 1][15]5.0
3[3, 1][5, 15]4.0

After the fourth insert the sorted stream is 1, 3, 5, 15, so the median is (3 + 5) / 2 = 4.0. The heaps never need sorting, which is where the efficiency comes from.

Why this beats the obvious alternatives

ApproachaddmedianProblem
Sorted list with bisect.insortO(n) shiftO(1)At 1,000,000 elements an insert shifts about 500,000 pointers on average
Re-sort on each queryO(n log n)O(n log n)Pays the full sort even if the median is read once
Two heapsO(log n)O(1)About 20 comparisons per insert at 1,000,000 elements

A balanced binary search tree also gives O(log n) insertion, but finding the median needs order statistics on subtree sizes, which standard library trees in Java and Python do not expose. Two heaps get the median from the heap roots with no extra bookkeeping.

Failure modes and limits

Duplicates are handled naturally because the invariant is on values, not distinct keys. An empty stream must be rejected explicitly, as the code above does, since reading lo[0] would otherwise raise an opaque IndexError.

Concurrency is the real trap. If two threads call add_num at once, the size invariant can break between the push and the rebalance, and the median silently returns a wrong value. Guard both methods with a lock, or confine the finder to one thread and publish results through a queue.

Deletions break the design. Removing an arbitrary value from the middle of a heap is O(n) to locate, and lazy deletion with a hash map of pending removals adds complexity that usually signals a different data structure. If the interviewer asks for deletions or for the 90th percentile, say so plainly: deletions point to an order-statistic tree, and arbitrary percentiles over a stream point to a quantile sketch such as t-digest, which trades exactness for bounded memory. For exact medians with insertions only, two heaps are the answer to defend.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7Write a function that takes a binary tree and returns the kth smallest element in the tree?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

I would first clarify whether the tree is a binary search tree. Kth smallest only has a cheap answer under that assumption, because an inorder traversal of a BST visits values in sorted order. If it is an arbitrary binary tree, inorder gives no ordering and I would need to collect all values and select the kth, for example with heapq.nsmallest in O(n log k) time.

Assuming a BST, possibly with duplicates, I would use an iterative inorder traversal and stop as soon as I reach the kth node. That is O(h + k) time and O(h) extra space, where h is the tree height, and it avoids recursion limits on a skewed tree.

Python
# Python 3.11, checked against a standard BST node with .val, .left, .right
def kth_smallest(root, k):
    if k < 1:
        raise ValueError("k must be at least 1")
    stack = []
    cur = root
    while cur is not None or stack:
        while cur is not None:
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        k -= 1
        if k == 0:
            return cur.val
        cur = cur.right
    raise ValueError("k exceeds the number of nodes")

Worked trace

For this BST, with k = 3:

      5
     / \
    3   7
   / \   \
  2   4   8
StepActionVisited in orderRemaining k
1descend left from 5, 3, 222
2pop 2, move right (null)2, 31
3pop 3, move right to 42, 3, 40, return 4

The traversal never visits 5, 7 or 8. That early exit is the main saving over sorting the whole tree.

Alternatives and when to use them

ApproachTimeExtra spaceWhen it fits
Iterative inorder, early exitO(h + k)O(h)Default choice, handles skewed trees
Recursive inorderO(h + k)O(h) call stackShorter to write, risks RecursionError around depth 1000 in CPython
Augmented subtree sizesO(h) per query after O(n) buildO(n) stored sizesRepeated queries on a static tree you control
Collect and sort / heapO(n log n) or O(n log k)O(n) or O(k)Tree is not a BST, or ordering cannot be trusted

With augmented sizes, each node stores size = 1 + size(left) + size(right). To find kth smallest, compare k with size(left) + 1. Go left if k is smaller, return the current node if equal, otherwise go right with k - size(left) - 1. That turns each query into a single root to leaf walk, at the cost of maintaining sizes on every insert and delete. I would only propose it if the interviewer says the same tree will be queried many times.

Failure modes to name

Duplicates count as separate elements, so a tree with three copies of 4 returns 4 for each of the positions those copies occupy in inorder order. That matches the usual definition and is worth stating, since some candidates deduplicate.

Invalid k needs an explicit decision. k = 0, negative k, and k larger than the node count should raise rather than return None, because a silent None gets mistaken for a stored value downstream. An empty tree hits the same path and raises the same error.

A degenerate BST, for example a chain of 10,000 nodes inserted in sorted order, makes h equal to n. The iterative version still works, using O(n) stack space, while the recursive version fails. If the data can arrive in sorted order, I would mention balancing the tree or using an order statistic tree instead of relying on the input shape.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-8Tell me about a time you encountered a significant technical challenge or bug in a project that was critical for Prosus or one of its portfolio companies, and how you diagnosed, addressed, and resolved it?

Reported in Prosus Software Engineer Interview Questions

The 90-second answer

At my previous role I owned checkout payments for a marketplace doing about 12,000 orders an hour at peak. During a flash sale, finance flagged duplicate wallet debits. Our duplicate rate went from a baseline of 0.02% to 3.1% in 40 minutes, roughly 370 duplicate charges. Checkout was still up, which made it worse, because retries kept succeeding.

I was on call. I froze the deploy, checked whether the processor was double charging or we were calling it twice, and found the second. A client timeout at 2 seconds triggered a retry with a new payment attempt ID. Our gateway treated it as a new payment, so one order got two authorisations. I stopped retries at the gateway, reconciled every attempt ID against the processor, refunded the duplicates, and shipped a fix that made the idempotency key the payment identity. We added a unique constraint in the database so the fix holds even if the gateway code regresses.

What I found

The first check ruled out the processor. Their ledger showed two distinct authorisation IDs per affected order, created 600 to 900 ms apart. That pointed at us.

Client times out after 2s Client retries with new attempt ID Gateway creates second payment Processor authorises twice Order marked paid, wallet debited twice
TimeSignalWhat it told me
14:02Duplicate rate 0.02% to 3.1%Correlated with sale traffic, not a deploy
14:09Two authorisation IDs per order, 600 to 900 ms apartProcessor was not replaying, we were re-calling
14:17Retries carried a fresh attempt_id each timeClient and gateway disagreed on what a retry was
14:24No unique constraint on (order_id, idempotency_key)Nothing in storage stopped the second insert

I pulled 500 affected orders and confirmed the pattern in every case: first attempt timed out at the client but completed at the processor, retry created a second payment, and the order row pointed at the second one. The first debit was orphaned.

The fix

Immediate containment was to disable automatic retry on payment creation and to reconcile by order ID before any refund. That stopped new duplicates within about 15 minutes. Refunds went out from the reconciliation report, not by hand, so finance could audit each one against a processor authorisation ID.

The permanent fix moved identity into the database. The client now sends one Idempotency-Key per checkout intent and reuses it on every retry. The gateway inserts the key and the payment in a single transaction.

SQL
-- PostgreSQL, checked against 15
CREATE UNIQUE INDEX payments_order_idempotency_key
    ON payments (order_id, idempotency_key);

INSERT INTO payments (order_id, idempotency_key, amount_cents, status)
VALUES ($1, $2, $3, 'pending')
ON CONFLICT (order_id, idempotency_key) DO NOTHING
RETURNING id;

If the insert returns no row, the key already exists. The gateway loads the existing payment and returns its status instead of calling the processor again. If the processor call times out, we query the processor by that same key before deciding anything. A timeout is treated as unknown, never as failure.

I considered fixing only the client timeout, from 2 seconds to 5. That would have reduced retries but left the race intact on slow networks. The unique constraint costs one indexed insert per payment, which we measured at under 1 ms at our volume, and it removes the whole class of bug.

Follow-up

We added an alert on duplicate authorisations per order, a daily reconciliation job comparing our payments table to the processor ledger, and a load test that injects 30% timeouts on payment calls. Duplicate rate stayed at zero over the next six months, including the next sale. The lesson I took from it is that retry safety has to be enforced where the money moves, not assumed from client behaviour.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9Describe a situation where you had a technical disagreement with a colleague or team lead regarding an architectural decision or implementation detail for a Prosus project, and how you approached it and what you learned?

Reported in Prosus Software Engineer Interview Questions

I will use a checkout change I worked on for a marketplace listing service, because the disagreement was about architecture, not taste, and both sides had a point.

We had a product page that called the pricing service synchronously on every request. At peak we saw p99 at 1.8 seconds for 12,000 requests per minute, and the pricing service was timing out under load. My team lead proposed adding a Redis cache in front of pricing, with a 60 second TTL. I argued for fixing the upstream query and adding a database index first, then measuring, before we introduced a cache we would have to invalidate.

My concern was not that caching is wrong. It was that we did not know why it was slow. If the slow path was a missing index, a cache would hide it for hot products and leave cold products just as slow. It would also create a stale price problem. A seller could change a price, and a buyer would see the old price for up to 60 seconds. For a marketplace that takes commission on the transaction, that is a correctness issue, not just a performance one.

How I approached it

I did not start by defending my preference. I asked for two days to profile the service and put numbers on the table. We added timing around the database call and checked the query plan in production-like data. The pricing lookup was doing a sequential scan on a table with 40 million rows because the query filtered on seller_id and category, but the index only covered seller_id. That explained most of the latency.

I then wrote up three options with the same traffic assumption, 12,000 requests per minute at peak, and labelled the figures as estimates from our load test:

Optionp99 estimateStale price riskOperational cost
Index only220 msNoneOne migration, low
Redis cache, 60 s TTL35 ms for hot keys, 1.8 s for cold keysUp to 60 sCache invalidation, memory, new failure mode
Index plus short cache, 5 s TTL, invalidate on write60 msUp to 5 s, plus invalidation bugsMedium

The mermaid diagram below is the flow we ended up shipping:

Yes No Product page request Pricing service Cache hit? Return cached price Indexed DB lookup Store in cache 5 s Price update Invalidate cache key

We shipped the index first and re-ran the load test. p99 dropped from 1.8 seconds to 240 ms without any cache. That gave us headroom. We then added the 5 second cache with write-through invalidation, not because we needed it that day, but because we expected traffic to double during a sale event. The short TTL limited the stale window, and invalidation on write handled the common case where a seller edits their own listing.

What I learned

My team lead was right that we needed headroom for the sale event, and I was right that we should not cache a broken query. The compromise worked because we separated the two decisions. Fix the root cause, measure, then add the cache for a stated reason with a stated stale window.

I also learned to write the disagreement down as a short ADR with the numbers and the rollback plan. When the cache later had an incident, a key pattern bug caused a 30 percent hit rate drop for an hour, we could see in the ADR that the cache was an optimisation, not a dependency. We could disable it with a flag and fall back to the indexed query at 240 ms p99 instead of paging on a cache outage. That would not have been true if we had cached first and never fixed the query.

If I faced the same split again, I would do the same thing: ask for a time-boxed investigation, bring a trace and a cost table, and make the decision reversible. I would also be quicker to name the other person's constraint early. In this case it was the sale deadline, and I spent the first day arguing about indexes while he was worried about a date I had not asked about.

Curated: · Written: · Reviewed:

Difficulty: Easy

Curated: · Written: · Reviewed: