PhonePe Coding Round Questions with Solutions
Last updated 2026-11-19
PhonePe is built around UPI payments, merchant acceptance and settlement, which makes correctness under retries and partial failure the central engineering concern. Candidate write-ups describe rounds that combine data-structure problems with a low-level design task where you write working object-oriented code for a small system within an hour or more. The ten problems below stay inside that payments world: matching two statements, surviving a duplicate request, reading a QR payload, scheduling payouts, spotting circular transfers and settling a group's debts.
They are original practice problems, not copies of any test. Each has Python and Java code, a stated cost and the failure that most often costs marks. For design theory and HR preparation read PhonePe interview questions, and for more design patterns see low level design interview questions.
Designing for retries, not for the happy path
A payment request can be sent twice, arrive late or fail halfway, so the interesting design questions are about what happens the second time. Before writing classes, list which operations must be idempotent, which must be atomic, and which values must never be negative. The processor and ledger below are built around those three lists.
For algorithmic problems, state the cost before coding and test one example by hand. Candidate accounts say interviewers often follow up with a harder variant, so keep the code easy to change: small functions, clear names, no hidden global state.
Hiring status
Open roles are on PhonePe's careers page at phonepe.com/careers, and sourced news is at PhonePe hiring. These round formats are candidate-reported and may differ for your role.
PhonePe Coding Round Questions with Solutions: questions with worked answers
1 Reconcile the payment platform's ledger against a bank statement, listing entries that appear on only one side.
mediumTreat each side as a multiset of (transaction id, amount) pairs and subtract one from the other in both directions. What remains in the first difference is in the ledger but not the bank; what remains in the second is the reverse. An id that shows up in both leftovers means the two sides disagree on its amount. O(n) with hashing. Using sets instead of counters hides genuine duplicates, and comparing ids alone misses amount mismatches.
pythonfrom collections import Counter def reconcile(ledger, bank): # lists of (txn_id, amount) a, b = Counter(ledger), Counter(bank) only_ledger = sorted((a - b).elements()) only_bank = sorted((b - a).elements()) return only_ledger, only_bankjavaimport java.util.*; static List<List<String>> reconcile(List<String> ledger, List<String> bank) { // entries like id:amount Map<String, Integer> diff = new TreeMap<>(); for (String e : ledger) diff.merge(e, 1, Integer::sum); for (String e : bank) diff.merge(e, -1, Integer::sum); List<String> onlyLedger = new ArrayList<>(), onlyBank = new ArrayList<>(); for (var en : diff.entrySet()) { for (int i = 0; i < en.getValue(); i++) onlyLedger.add(en.getKey()); for (int i = 0; i < -en.getValue(); i++) onlyBank.add(en.getKey()); } return List.of(onlyLedger, onlyBank); }2 Machine coding: a payment processor that is safe when the same request is retried.
hardClients attach a request id to each payment. Store, per id, the payload and the outcome. On a repeat with the same payload return the stored outcome without moving money again; on a repeat with a different payload return a distinct key-reuse error. Otherwise validate, debit, credit and record. Each call is O(1) and the whole body is one critical section. Recording only successes lets a retried failure succeed later, and checking the key after the debit double-charges.
pythonclass PaymentProcessor: def __init__(self, balances): self.bal, self.seen = dict(balances), {} def pay(self, request_id, payer, payee, amount): payload = (payer, payee, amount) if request_id in self.seen: old_payload, result = self.seen[request_id] return result if old_payload == payload else 'KEY_REUSED' if amount <= 0 or payer == payee: result = 'INVALID' elif self.bal.get(payer, 0) < amount: result = 'INSUFFICIENT' else: self.bal[payer] -= amount self.bal[payee] = self.bal.get(payee, 0) + amount result = 'OK' self.seen[request_id] = (payload, result) return resultjavaimport java.util.*; class PaymentProcessor { private final Map<String, Long> bal; private final Map<String, String[]> seen = new HashMap<>(); // id -> {payload, result} PaymentProcessor(Map<String, Long> balances) { bal = new HashMap<>(balances); } synchronized String pay(String requestId, String payer, String payee, long amount) { String payload = payer + ">" + payee + ":" + amount; String[] prev = seen.get(requestId); if (prev != null) return prev[0].equals(payload) ? prev[1] : "KEY_REUSED"; String result; if (amount <= 0 || payer.equals(payee)) result = "INVALID"; else if (bal.getOrDefault(payer, 0L) < amount) result = "INSUFFICIENT"; else { bal.merge(payer, -amount, Long::sum); bal.merge(payee, amount, Long::sum); result = "OK"; } seen.put(requestId, new String[]{payload, result}); return result; } }3 Parse a QR payload made of two-digit tag, two-digit length and a value, repeated.
mediumRead the tag from two characters, the length from the next two, then exactly that many characters as the value, and advance by four plus the length. Repeat to the end of the string. Reject a payload whose tag or length is not numeric, whose header is cut short, or whose value runs past the end. Linear time. Using split on a delimiter fails because values may contain any character, and trusting the declared length without a bounds check turns malformed input into an exception deep in the code.
pythondef parse_tlv(s): out, i = {}, 0 while i < len(s): if i + 4 > len(s): raise ValueError('truncated header') tag, size = s[i:i + 2], s[i + 2:i + 4] if not (tag.isdigit() and size.isdigit()): raise ValueError('non-numeric tag or length') n = int(size) if i + 4 + n > len(s): raise ValueError('value runs past end') out[tag] = s[i + 4:i + 4 + n] i += 4 + n return outjavaimport java.util.*; static Map<String, String> parseTlv(String s) { Map<String, String> out = new LinkedHashMap<>(); int i = 0; while (i < s.length()) { if (i + 4 > s.length()) throw new IllegalArgumentException("truncated header"); String tag = s.substring(i, i + 2), size = s.substring(i + 2, i + 4); if (!tag.chars().allMatch(Character::isDigit) || !size.chars().allMatch(Character::isDigit)) throw new IllegalArgumentException("non-numeric tag or length"); int n = Integer.parseInt(size); if (i + 4 + n > s.length()) throw new IllegalArgumentException("value runs past end"); out.put(tag, s.substring(i + 4, i + 4 + n)); i += 4 + n; } return out; }4 Fewest time slots to run payout jobs when two jobs for the same bank must be at least n slots apart.
hardOnly the most frequent bank constrains the schedule. If it has m jobs, they occupy m-1 gaps of n+1 slots each plus a final row of as many slots as there are banks tied for that maximum. The answer is that figure, or the total job count if it is larger because other jobs fill the gaps completely. O(jobs). Simulating with a heap also works. The usual slip is forgetting the final row for ties, or forgetting the lower bound of the job count.
pythonfrom collections import Counter def min_slots(banks, n): cnt = Counter(banks) top = max(cnt.values()) ties = sum(1 for v in cnt.values() if v == top) return max(len(banks), (top - 1) * (n + 1) + ties)javastatic int minSlots(char[] banks, int n) { int[] cnt = new int[128]; int top = 0; for (char c : banks) top = Math.max(top, ++cnt[c]); int ties = 0; for (int v : cnt) if (v == top) ties++; return Math.max(banks.length, (top - 1) * (n + 1) + ties); }5 Detect whether a set of account-to-account transfers contains a cycle of money.
mediumRun a depth-first search with three states per account: unvisited, on the current path, finished. Meeting an account that is on the current path means a cycle. An explicit stack of (node, neighbour iterator) pairs avoids recursion limits on long chains. O(V + E). Marking nodes as simply visited, with only two states, reports a cycle whenever two paths merge, which is a false positive in a graph that is merely diamond-shaped.
pythondef has_cycle(n, edges): adj = [[] for _ in range(n)] for u, v in edges: adj[u].append(v) state = [0] * n # 0 new, 1 on path, 2 done for s in range(n): if state[s]: continue state[s] = 1 stack = [(s, iter(adj[s]))] while stack: u, it = stack[-1] for v in it: if state[v] == 1: return True if state[v] == 0: state[v] = 1 stack.append((v, iter(adj[v]))) break else: state[u] = 2 stack.pop() return Falsejavaimport java.util.*; static boolean hasCycle(int n, int[][] edges) { List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int[] e : edges) adj.get(e[0]).add(e[1]); int[] state = new int[n], idx = new int[n]; for (int s = 0; s < n; s++) { if (state[s] != 0) continue; ArrayDeque<Integer> stack = new ArrayDeque<>(); stack.push(s); state[s] = 1; while (!stack.isEmpty()) { int u = stack.peek(); if (idx[u] < adj.get(u).size()) { int v = adj.get(u).get(idx[u]++); if (state[v] == 1) return true; if (state[v] == 0) { state[v] = 1; stack.push(v); } } else { state[u] = 2; stack.pop(); } } } return false; }6 Choose the chain of payment gateways with the highest overall success probability between two endpoints.
mediumSuccess probabilities multiply along a path, and each is at most one, so extending a path never improves it; that is the property Dijkstra needs. Run Dijkstra with a max-heap on the probability, relaxing a neighbour when the product through the current node beats its best. The first time the destination is popped, its probability is final. O((V + E) log V). Adding probabilities, or minimising instead of maximising, is the natural wrong turn. Return zero if the destination is unreachable.
pythonimport heapq from collections import defaultdict def best_route(links, src, dst): # links: (a, b, probability), two-way adj = defaultdict(list) for a, b, p in links: adj[a].append((b, p)) adj[b].append((a, p)) best = {src: 1.0} heap = [(-1.0, src)] while heap: neg, u = heapq.heappop(heap) if u == dst: return -neg if -neg < best.get(u, 0): continue for v, p in adj[u]: if -neg * p > best.get(v, 0): best[v] = -neg * p heapq.heappush(heap, (-best[v], v)) return 0.0javaimport java.util.*; static double bestRoute(int n, double[][] links, int src, int dst) { // {a, b, p} List<List<double[]>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (double[] l : links) { adj.get((int) l[0]).add(new double[]{l[1], l[2]}); adj.get((int) l[1]).add(new double[]{l[0], l[2]}); } double[] best = new double[n]; best[src] = 1.0; PriorityQueue<double[]> pq = new PriorityQueue<>((a, b) -> Double.compare(b[0], a[0])); pq.add(new double[]{1.0, src}); while (!pq.isEmpty()) { double[] cur = pq.poll(); int u = (int) cur[1]; if (u == dst) return cur[0]; if (cur[0] < best[u]) continue; for (double[] e : adj.get(u)) { double cand = cur[0] * e[1]; if (cand > best[(int) e[0]]) { best[(int) e[0]] = cand; pq.add(new double[]{cand, e[0]}); } } } return 0.0; }7 Compute cashback as a percentage of a payment in paise, rounded half up and capped.
easyExpress the rate in basis points (hundredths of a percent) so 1.5 percent is 150. Multiply the amount in paise by the rate, add 5000 to round half up, divide by 10,000 using integer division, then take the smaller of that and the cap. Constant time with no floating point. The mistakes are using a float percentage that turns 0.5 paise into 0 or 1 unpredictably, and capping before rounding, which lets a rounded value exceed the cap by one.
pythondef cashback(amount_paise, rate_bp, cap_paise): raw = (amount_paise * rate_bp + 5000) // 10000 return min(raw, cap_paise)javastatic long cashback(long amountPaise, int rateBp, long capPaise) { long raw = (amountPaise * rateBp + 5000) / 10000; return Math.min(raw, capPaise); }8 Machine coding: a double-entry ledger where every journal entry must balance and customer accounts cannot go negative.
hardA journal entry is a list of (account, signed amount) lines whose total is zero. Posting validates three things before touching state: the entry id is new, the lines sum to zero, and no protected account would end below zero after the whole entry is applied. Only then apply every line. Aggregate lines per account first, since one entry may touch an account twice. O(lines). Applying lines one by one and checking as you go leaves half an entry behind when a later line fails.
pythonfrom collections import defaultdict class Ledger: def __init__(self, protected=()): self.bal, self.seen, self.protected = defaultdict(int), set(), set(protected) def post(self, entry_id, lines): # lines: [(account, signed_paise)] if entry_id in self.seen: raise ValueError('duplicate entry') if sum(d for _, d in lines) != 0: raise ValueError('entry does not balance') net = defaultdict(int) for acct, d in lines: net[acct] += d for acct, d in net.items(): if acct in self.protected and self.bal[acct] + d < 0: raise ValueError('insufficient funds in ' + acct) for acct, d in net.items(): self.bal[acct] += d self.seen.add(entry_id)javaimport java.util.*; class Ledger { private final Map<String, Long> bal = new HashMap<>(); private final Set<String> seen = new HashSet<>(), protectedAccts; Ledger(Set<String> protectedAccts) { this.protectedAccts = protectedAccts; } void post(String id, String[] accounts, long[] deltas) { if (seen.contains(id)) throw new IllegalArgumentException("duplicate entry"); long sum = 0; Map<String, Long> net = new HashMap<>(); for (int i = 0; i < accounts.length; i++) { sum += deltas[i]; net.merge(accounts[i], deltas[i], Long::sum); } if (sum != 0) throw new IllegalArgumentException("entry does not balance"); for (var e : net.entrySet()) if (protectedAccts.contains(e.getKey()) && bal.getOrDefault(e.getKey(), 0L) + e.getValue() < 0) throw new IllegalArgumentException("insufficient funds in " + e.getKey()); for (var e : net.entrySet()) bal.merge(e.getKey(), e.getValue(), Long::sum); seen.add(id); } long balance(String account) { return bal.getOrDefault(account, 0L); } }9 Machine coding: show the top k merchants by payment volume over the last 24 hours.
hardGroup payments into hourly buckets, each a map from merchant to amount, and keep running totals per merchant. Recording adds to the current bucket and the totals; before every read or write, evict buckets older than 24 hours and subtract their amounts from the totals. The top k are then the k largest totals, with ties broken by name for stable output. Memory depends on hours and merchants, not on payment count. Recomputing from raw events on each request, or never evicting zero totals, are the usual faults.
pythonimport heapq from collections import Counter, deque class RollingTop: def __init__(self, hours=24): self.hours, self.buckets, self.totals = hours, deque(), Counter() def _evict(self, hour): while self.buckets and self.buckets[0][0] <= hour - self.hours: _, c = self.buckets.popleft() for m, amt in c.items(): self.totals[m] -= amt if self.totals[m] == 0: del self.totals[m] def record(self, merchant, ts, amount): hour = ts // 3600 self._evict(hour) if not self.buckets or self.buckets[-1][0] != hour: self.buckets.append((hour, Counter())) self.buckets[-1][1][merchant] += amount self.totals[merchant] += amount def top(self, k, now): self._evict(now // 3600) return heapq.nsmallest(k, self.totals.items(), key=lambda kv: (-kv[1], kv[0]))javaimport java.util.*; class RollingTop { private static class Bucket { long hour; Map<String, Long> m = new HashMap<>(); Bucket(long h) { hour = h; } } private final int hours; private final ArrayDeque<Bucket> buckets = new ArrayDeque<>(); private final Map<String, Long> totals = new HashMap<>(); RollingTop(int hours) { this.hours = hours; } private void evict(long hour) { while (!buckets.isEmpty() && buckets.peekFirst().hour <= hour - hours) { for (var e : buckets.pollFirst().m.entrySet()) { long left = totals.merge(e.getKey(), -e.getValue(), Long::sum); if (left == 0) totals.remove(e.getKey()); } } } void record(String merchant, long ts, long amount) { long hour = ts / 3600; evict(hour); if (buckets.isEmpty() || buckets.peekLast().hour != hour) buckets.addLast(new Bucket(hour)); buckets.peekLast().m.merge(merchant, amount, Long::sum); totals.merge(merchant, amount, Long::sum); } List<String> top(int k, long now) { evict(now / 3600); List<Map.Entry<String, Long>> all = new ArrayList<>(totals.entrySet()); all.sort((a, b) -> !a.getValue().equals(b.getValue()) ? Long.compare(b.getValue(), a.getValue()) : a.getKey().compareTo(b.getKey())); List<String> out = new ArrayList<>(); for (int i = 0; i < Math.min(k, all.size()); i++) out.add(all.get(i).getKey()); return out; } }10 Fewest transfers needed to settle a group's debts, given who paid whom.
hardNet every person's balance from the payments and drop the zeros; what remains sums to zero. Backtrack: take the first non-zero balance and try cancelling it against each later balance of the opposite sign, moving the combined amount onto that person and recursing on the rest, then undo. Skip a candidate whose balance equals one already tried at this level. Exponential in the worst case, but groups are small. A greedy largest-creditor against largest-debtor rule is fast but can use more transfers than needed.
pythonfrom collections import Counter def min_settlements(payments): # (payer, payee, amount) bal = Counter() for a, b, x in payments: bal[a] -= x bal[b] += x debts = [v for v in bal.values() if v] def go(i): while i < len(debts) and debts[i] == 0: i += 1 if i == len(debts): return 0 best, tried = float('inf'), set() for j in range(i + 1, len(debts)): if debts[i] * debts[j] < 0 and debts[j] not in tried: tried.add(debts[j]) debts[j] += debts[i] best = min(best, 1 + go(i + 1)) debts[j] -= debts[i] return best return go(0)javaimport java.util.*; static int minSettlements(int[][] payments) { // {payer, payee, amount} Map<Integer, Integer> bal = new HashMap<>(); for (int[] p : payments) { bal.merge(p[0], -p[2], Integer::sum); bal.merge(p[1], p[2], Integer::sum); } List<Integer> list = new ArrayList<>(); for (int v : bal.values()) if (v != 0) list.add(v); int[] debts = list.stream().mapToInt(Integer::intValue).toArray(); return settle(debts, 0); } private static int settle(int[] d, int i) { while (i < d.length && d[i] == 0) i++; if (i == d.length) return 0; int best = Integer.MAX_VALUE; Set<Integer> tried = new HashSet<>(); for (int j = i + 1; j < d.length; j++) { if ((long) d[i] * d[j] < 0 && tried.add(d[j])) { d[j] += d[i]; best = Math.min(best, 1 + settle(d, i + 1)); d[j] -= d[i]; } } return best; }
Frequently asked questions
What does idempotent mean for a payment API?
Repeating the same request has the same effect as making it once. In practice a client-supplied request id is stored with its outcome, so a retry returns the first result and never moves money twice.
How long should I spend on the design before coding?
Around five to ten minutes in a ninety-minute build: list the nouns as classes, the verbs as methods, and the invariants such as no negative balances. Then code the main flow end to end first.
Should concurrency appear in my machine-coding answer?
Yes, at least explicitly. A single lock around each mutating method, with a comment on why, shows awareness. Finer-grained locking is a follow-up, not a starting requirement.
Is a greedy settlement algorithm ever acceptable?
It is acceptable if you say that it is not guaranteed minimal and the interviewer is fine with that. When the question asks for the fewest transfers, use the backtracking approach.
Sources
Related guides
More in Company Interview Questions
- PhonePe Interview Questions and Answers
- Postman Coding Round Questions With Solutions
- Postman Interview Questions and Answers
- Publicis Sapient Coding Round Questions
- Publicis Sapient Interview Questions with Answers
- PwC coding round questions
- PwC interview questions and answers
- Qualcomm Coding Round Questions with Solutions
- Qualcomm Interview Questions and Answers for India Software Roles
- Razorpay Coding Round Questions with Solutions
- Razorpay Interview Questions and Answers
- Salesforce Coding Round Questions with Solutions in Python and Java