Autocoder

Razorpay Coding Round Questions with Solutions

Last updated 2026-11-19

A payments company cares about problems where a duplicate request, a rounding slip or a retry storm costs real money. Candidate write-ups describe Razorpay's engineering process as an online screen with a couple of data structures problems, a machine-coding or low-level design session, and deeper technical rounds. The eleven problems below are written around that flavour: charges that must not run twice, amounts that must add up to the last paisa, and ledgers that must agree.

Each one is original practice material, not a copy of any test. For concept questions about gateways, settlements and webhooks, read Razorpay interview questions. For pacing a timed screen, see the online assessment guide.

Why payments problems feel different

Most of these tasks are small, but the grading is strict about edge cases that a leaderboard problem would ignore. Money is held as integers (paise), never floats. Operations that a client might retry are written so that running them twice gives the same outcome as running them once. State changes follow a fixed set of allowed moves, and anything outside that set is rejected loudly.

When you practise, say these properties out loud before typing: what is the unit, what happens on a replay, what happens at a boundary such as an empty list or a zero amount. Interviewers on machine-coding rounds tend to reward that habit as much as a clean class layout.

A sensible order for the set

Hiring status

This site holds no sourced hiring statement for Razorpay. Current roles are listed on the company's own jobs page at razorpay.com/jobs. Everything above about round shape is candidate-reported and may have changed.

Razorpay Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Make a charge API idempotent using a client-supplied key.

    medium

    Keep a map from idempotency key to the first result. On a repeat with the same key and the same amount, return the stored result without charging again. If the key is reused with a different amount, reject it, since that is a client bug. Lookup and insert are O(1). In production the check-and-insert must be atomic, which is why the Java version is synchronized. Common mistakes: storing only a boolean so the replay cannot return the original payment id, and ignoring payload mismatch.

    python
    class Gateway:
        def __init__(self):
            self.by_key = {}
            self.counter = 0
    
        def charge(self, key, amount):
            prior = self.by_key.get(key)
            if prior is not None:
                if prior['amount'] != amount:
                    raise ValueError('idempotency key reused with a different amount')
                return prior
            self.counter += 1
            result = {'id': 'pay_%d' % self.counter, 'amount': amount, 'status': 'captured'}
            self.by_key[key] = result
            return result
    java
    import java.util.*;
    
    class Gateway {
        static class Payment {
            final String id; final long amount;
            Payment(String id, long amount) { this.id = id; this.amount = amount; }
        }
        private final Map<String, Payment> byKey = new HashMap<>();
        private int counter = 0;
    
        synchronized Payment charge(String key, long amount) {
            Payment prior = byKey.get(key);
            if (prior != null) {
                if (prior.amount != amount) throw new IllegalArgumentException("key reused with different amount");
                return prior;
            }
            Payment p = new Payment("pay_" + (++counter), amount);
            byKey.put(key, p);
            return p;
        }
    }
  2. 2

    Split an amount in paise across payees by weight so the shares sum exactly to the total.

    medium

    Give each payee the floor of its proportional share, then hand the leftover paise one at a time to the payees with the largest fractional remainder (largest remainder method). The remainder of total*weight divided by the weight sum is the integer stand-in for the fraction. O(n log n) for the sort, O(n) space. Common mistakes: rounding each share independently so the sum drifts by a paisa, and using floats.

    python
    def split(total, weights):
        wsum = sum(weights)
        shares = [total * w // wsum for w in weights]
        left = total - sum(shares)
        order = sorted(range(len(weights)), key=lambda i: -(total * weights[i] % wsum))
        for i in order[:left]:
            shares[i] += 1
        return shares
    java
    import java.util.*;
    
    class Split {
        static long[] split(long total, long[] w) {
            long wsum = 0;
            for (long x : w) wsum += x;
            int n = w.length;
            long[] share = new long[n];
            long used = 0;
            for (int i = 0; i < n; i++) { share[i] = total * w[i] / wsum; used += share[i]; }
            Integer[] order = new Integer[n];
            for (int i = 0; i < n; i++) order[i] = i;
            final long ws = wsum;
            Arrays.sort(order, (a, b) -> Long.compare((total * w[b]) % ws, (total * w[a]) % ws));
            for (int k = 0; k < total - used; k++) share[order[k]]++;
            return share;
        }
    }
  3. 3

    Validate a card number with the Luhn checksum.

    easy

    Walk the digits from the right. Double every second digit; if the result exceeds 9 subtract 9. Add everything up and the number is valid when the total is divisible by 10. Single pass, O(n) time, O(1) space. Common mistakes: doubling from the left, which breaks for odd-length numbers, and not rejecting input that has non-digit characters.

    python
    def luhn_ok(num):
        if not num.isdigit():
            return False
        total = 0
        for pos, ch in enumerate(reversed(num)):
            d = int(ch)
            if pos % 2 == 1:
                d *= 2
                if d > 9:
                    d -= 9
            total += d
        return total % 10 == 0
    java
    class Luhn {
        static boolean ok(String num) {
            int total = 0;
            for (int i = num.length() - 1, pos = 0; i >= 0; i--, pos++) {
                char c = num.charAt(i);
                if (c < '0' || c > '9') return false;
                int d = c - '0';
                if (pos % 2 == 1) { d *= 2; if (d > 9) d -= 9; }
                total += d;
            }
            return total % 10 == 0;
        }
    }
  4. 4

    Build a per-merchant token-bucket rate limiter.

    medium

    Each key owns a bucket holding up to capacity tokens that refills at a fixed rate. On every call, add rate times elapsed seconds (capped at capacity), then spend one token if at least one is available. This allows short bursts while enforcing an average rate. O(1) per call, O(keys) space. Common mistakes: refilling on a timer thread instead of lazily, forgetting the cap, and sharing one bucket across all merchants.

    python
    class RateLimiter:
        def __init__(self, capacity, per_second):
            self.cap = capacity
            self.rate = per_second
            self.state = {}
    
        def allow(self, key, now):
            tokens, last = self.state.get(key, (self.cap, now))
            tokens = min(self.cap, tokens + (now - last) * self.rate)
            ok = tokens >= 1
            if ok:
                tokens -= 1
            self.state[key] = (tokens, now)
            return ok
    java
    import java.util.*;
    
    class RateLimiter {
        private final double cap, rate;
        private final Map<String, double[]> state = new HashMap<>();
        RateLimiter(double cap, double perSecond) { this.cap = cap; this.rate = perSecond; }
    
        boolean allow(String key, double now) {
            double[] s = state.computeIfAbsent(key, k -> new double[]{cap, now});
            double tokens = Math.min(cap, s[0] + (now - s[1]) * rate);
            boolean ok = tokens >= 1;
            if (ok) tokens -= 1;
            s[0] = tokens; s[1] = now;
            return ok;
        }
    }
  5. 5

    Compare a bank statement with the internal ledger and list every mismatch.

    medium

    Load both sides into maps keyed by reference. Anything only in the bank file is unrecorded, anything only in the ledger is unsettled, and keys present in both with different amounts are amount mismatches. Two passes, O(n + m) time and space. Common mistakes: sorting both lists and walking them in step, which breaks on repeated references, and comparing amounts that are in different units.

    python
    def reconcile(bank, ledger):
        b, l = dict(bank), dict(ledger)
        only_bank = sorted(r for r in b if r not in l)
        only_ledger = sorted(r for r in l if r not in b)
        differ = sorted(r for r in b if r in l and b[r] != l[r])
        return only_bank, only_ledger, differ
    java
    import java.util.*;
    
    class Reconcile {
        static List<String> run(Map<String, Long> bank, Map<String, Long> ledger) {
            List<String> out = new ArrayList<>();
            for (String ref : new TreeSet<>(bank.keySet())) {
                if (!ledger.containsKey(ref)) out.add(ref + ":missing_in_ledger");
                else if (!bank.get(ref).equals(ledger.get(ref))) out.add(ref + ":amount_differs");
            }
            for (String ref : new TreeSet<>(ledger.keySet()))
                if (!bank.containsKey(ref)) out.add(ref + ":missing_in_bank");
            return out;
        }
    }
  6. 6

    Flag a charge as a suspected duplicate if the same card is billed the same amount within 60 seconds.

    easy

    Process events in time order and remember the latest timestamp for each card-and-amount pair. If the gap to the previous matching event is 60 seconds or less, flag the current index. Always update the stored timestamp, so a run of repeats keeps flagging. O(n) time, O(distinct pairs) space. Common mistakes: comparing every pair of events, and storing the first timestamp instead of the latest.

    python
    def suspected_duplicates(events, window=60):
        last, flagged = {}, []
        for i, (ts, card, amount) in enumerate(events):
            k = (card, amount)
            if k in last and ts - last[k] <= window:
                flagged.append(i)
            last[k] = ts
        return flagged
    java
    import java.util.*;
    
    class Dupes {
        static List<Integer> flag(long[] ts, String[] card, long[] amount, long window) {
            Map<String, Long> last = new HashMap<>();
            List<Integer> out = new ArrayList<>();
            for (int i = 0; i < ts.length; i++) {
                String k = card[i] + "|" + amount[i];
                Long prev = last.get(k);
                if (prev != null && ts[i] - prev <= window) out.add(i);
                last.put(k, ts[i]);
            }
            return out;
        }
    }
  7. 7

    Find the cheapest routing cost between two payment rails using at most k intermediate hops.

    hard

    Run Bellman-Ford for k+1 rounds. Each round relaxes every edge using a copy of the previous round's distances, so a path can grow by at most one edge per round. O(k * E) time, O(V) space. Common mistakes: relaxing in place, which lets a path use more than k hops within one round, and returning infinity instead of -1 when the target is unreachable.

    python
    def cheapest(n, edges, src, dst, k):
        INF = float('inf')
        dist = [INF] * n
        dist[src] = 0
        for _ in range(k + 1):
            nxt = dist[:]
            for u, v, cost in edges:
                if dist[u] + cost < nxt[v]:
                    nxt[v] = dist[u] + cost
            dist = nxt
        return -1 if dist[dst] == INF else dist[dst]
    java
    import java.util.*;
    
    class Route {
        static long cheapest(int n, int[][] edges, int src, int dst, int k) {
            long INF = Long.MAX_VALUE / 4;
            long[] dist = new long[n];
            Arrays.fill(dist, INF);
            dist[src] = 0;
            for (int round = 0; round <= k; round++) {
                long[] nxt = dist.clone();
                for (int[] e : edges)
                    if (dist[e[0]] + e[2] < nxt[e[1]]) nxt[e[1]] = dist[e[0]] + e[2];
                dist = nxt;
            }
            return dist[dst] >= INF ? -1 : dist[dst];
        }
    }
  8. 8

    Design an LRU cache for merchant configuration lookups.

    medium

    An ordered hash map gives O(1) get and put while tracking recency. Every read moves the key to the most recent end. When size exceeds capacity, evict from the oldest end. Space is O(capacity). Common mistakes: not refreshing recency on get, and building it from a plain list so that each access is O(n).

    python
    from collections import OrderedDict
    
    class ConfigCache:
        def __init__(self, capacity):
            self.cap = capacity
            self.data = OrderedDict()
    
        def get(self, key):
            if key not in self.data:
                return None
            self.data.move_to_end(key)
            return self.data[key]
    
        def put(self, key, value):
            self.data[key] = value
            self.data.move_to_end(key)
            if len(self.data) > self.cap:
                self.data.popitem(last=False)
    java
    import java.util.*;
    
    class ConfigCache<K, V> extends LinkedHashMap<K, V> {
        private final int cap;
        ConfigCache(int cap) { super(16, 0.75f, true); this.cap = cap; }
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > cap; }
    }
  9. 9

    Merge overlapping or touching settlement windows into the fewest windows.

    easy

    Sort by start. Keep a current window; if the next start is at most the current end, extend the end to the larger value, otherwise close the current one and begin a new one. O(n log n) time, O(n) space for output. Common mistakes: forgetting to take the max of the two ends when one window sits fully inside another, and skipping the sort.

    python
    def merge_windows(windows):
        out = []
        for s, e in sorted(windows):
            if out and s <= out[-1][1]:
                out[-1][1] = max(out[-1][1], e)
            else:
                out.append([s, e])
        return out
    java
    import java.util.*;
    
    class Windows {
        static List<int[]> merge(int[][] w) {
            Arrays.sort(w, (a, b) -> Integer.compare(a[0], b[0]));
            List<int[]> out = new ArrayList<>();
            for (int[] cur : w) {
                if (!out.isEmpty() && cur[0] <= out.get(out.size() - 1)[1])
                    out.get(out.size() - 1)[1] = Math.max(out.get(out.size() - 1)[1], cur[1]);
                else out.add(new int[]{cur[0], cur[1]});
            }
            return out;
        }
    }
  10. 10

    Validate a sequence of payment states against the allowed transitions.

    easy

    Encode the legal moves as a table: created goes to authorized or failed, authorized to captured, failed or voided, captured to refunded or partially_refunded, and partially_refunded to itself or refunded. Check each adjacent pair. O(n) time. Common mistakes: letting a failed or fully refunded payment move on, and not validating that the first state is created.

    python
    ALLOWED = {
        'created': {'authorized', 'failed'},
        'authorized': {'captured', 'failed', 'voided'},
        'captured': {'refunded', 'partially_refunded'},
        'partially_refunded': {'partially_refunded', 'refunded'},
    }
    
    def valid_flow(states):
        if not states or states[0] != 'created':
            return False
        return all(b in ALLOWED.get(a, set()) for a, b in zip(states, states[1:]))
    java
    import java.util.*;
    
    class Flow {
        static boolean step(String a, String b) {
            switch (a) {
                case "created": return b.equals("authorized") || b.equals("failed");
                case "authorized": return b.equals("captured") || b.equals("failed") || b.equals("voided");
                case "captured": return b.equals("refunded") || b.equals("partially_refunded");
                case "partially_refunded": return b.equals("partially_refunded") || b.equals("refunded");
                default: return false;
            }
        }
        static boolean valid(List<String> s) {
            if (s.isEmpty() || !s.get(0).equals("created")) return false;
            for (int i = 1; i < s.size(); i++) if (!step(s.get(i - 1), s.get(i))) return false;
            return true;
        }
    }
  11. 11

    Return the top k merchants by processed volume from a stream of (merchant, amount) events.

    medium

    Accumulate totals in a hash map, then pick the k largest with a size-k min-heap so the heap top is always the weakest of the current best. Break ties by merchant name for a stable answer. O(n + m log k) time for m distinct merchants, O(m) space. Common mistakes: sorting all merchants when k is tiny, and a max-heap of every merchant that wastes memory.

    python
    import heapq
    from collections import defaultdict
    
    def top_merchants(events, k):
        totals = defaultdict(int)
        for merchant, amount in events:
            totals[merchant] += amount
        return heapq.nsmallest(k, totals.items(), key=lambda kv: (-kv[1], kv[0]))
    java
    import java.util.*;
    
    class TopK {
        static List<String> top(String[] merchant, long[] amount, int k) {
            Map<String, Long> totals = new HashMap<>();
            for (int i = 0; i < merchant.length; i++) totals.merge(merchant[i], amount[i], Long::sum);
            PriorityQueue<Map.Entry<String, Long>> heap = new PriorityQueue<>((a, b) ->
                a.getValue().equals(b.getValue()) ? b.getKey().compareTo(a.getKey()) : Long.compare(a.getValue(), b.getValue()));
            for (Map.Entry<String, Long> e : totals.entrySet()) {
                heap.add(e);
                if (heap.size() > k) heap.poll();
            }
            LinkedList<String> out = new LinkedList<>();
            while (!heap.isEmpty()) out.addFirst(heap.poll().getKey());
            return out;
        }
    }

Frequently asked questions

What kind of coding problems does Razorpay ask?

Candidate reports describe a mix: standard data structures problems in the screen, then machine-coding or low-level design tasks where payment ideas such as idempotency, retries and ledgers come up. The set above follows that pattern, but formats change, so treat it as practice and not a prediction.

Do I need to know payments to clear the round?

You do not need domain expertise, but knowing why money is stored in integer units and why retries must be safe makes your answers sound deliberate. A short explanation of each is enough.

Which language should I use?

Use the one you can write fastest without looking up syntax. Python is quicker for the algorithmic questions, while Java suits class-heavy design tasks. Both are shown for every problem here.

How hard are the online screen problems compared with the machine-coding round?

The screen leans on algorithms under a timer, and the design round leans on clean classes, naming and extensibility within a longer window. Prepare separately for each: timed problem drills for the first, and building a small system from scratch for the second.

Where can I find current Razorpay openings?

Use the company's own jobs page at razorpay.com/jobs. Format details in this guide are candidate-reported and not an official description.

Sources

Related guides

More in Company Interview Questions

See all in this section