Autocoder

Ola Coding Round Questions with Solutions

Last updated 2026-11-19

A ride-hailing company spends its engineering effort on three questions: which driver should take this rider, how long will the trip take, and what should it cost. Ola's candidate-reported rounds are described as a DSA round followed by a role-specific technical discussion, though the sample behind that is small. The problems below borrow the three questions above and turn them into compact exercises on heaps, graphs, grids and dynamic programming.

They are original practice problems, not recalled ones. Each has Python and Java code, a stated cost and the mistakes worth avoiding. For concepts and HR preparation read Ola interview questions, and for a general routine see how to crack a technical interview.

The three questions behind mobility problems

Matching is a nearest-neighbour search that has to stay fast while every driver keeps moving, so look for heaps and spatial buckets. Routing is shortest-path on a weighted graph or a grid, so know Dijkstra, breadth-first search and when each applies. Pricing is arithmetic with slabs and smoothing, where integer money and boundary values decide correctness.

Time yourself at thirty minutes a problem, and after each one write the pattern and its cost in a single line. That list becomes a scannable reference before a real round.

Hiring status

Sourced hiring news sits at Ola hiring, and live roles are on the company's careers page. The round description above is candidate-reported from a small sample and may not reflect your track.

Ola Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Return the k drivers nearest to a rider from a list of coordinates.

    medium

    Compute squared distance to avoid square roots and keep a max-heap of size k holding the best candidates so far; when a closer driver arrives, replace the worst. O(n log k) time and O(k) space, better than a full sort when k is small. Break distance ties by driver id so output is deterministic. Using a min-heap of all n drivers and popping k works but costs O(n + k log n) memory-heavy, and using real distance with floats can reorder near ties.

    python
    import heapq
    
    def nearest_drivers(drivers, rx, ry, k):        # drivers: (id, x, y)
        def key(d):
            return ((d[1] - rx) ** 2 + (d[2] - ry) ** 2, d[0])
        return [d[0] for d in heapq.nsmallest(k, drivers, key=key)]
    java
    import java.util.*;
    
    static List<Integer> nearestDrivers(int[][] drivers, int rx, int ry, int k) {   // {id, x, y}
        PriorityQueue<long[]> worst = new PriorityQueue<>((a, b) -> a[0] != b[0] ? Long.compare(b[0], a[0]) : Long.compare(b[1], a[1]));
        for (int[] d : drivers) {
            long dx = d[1] - rx, dy = d[2] - ry;
            worst.add(new long[]{dx * dx + dy * dy, d[0]});
            if (worst.size() > k) worst.poll();
        }
        LinkedList<Integer> out = new LinkedList<>();
        while (!worst.isEmpty()) out.addFirst((int) worst.poll()[1]);
        return out;
    }
  2. 2

    Compute a surge multiplier from demand and supply over the last w minutes.

    easy

    Keep a queue of the last w per-minute (requests, available drivers) pairs with running totals of each. On every new minute, push it, subtract the pair that fell out of the window, and compute the ratio of total requests to total drivers. Clamp it between 1.0 and a cap such as 3.0 so price never drops below base or runs away. O(1) per update. Averaging the per-minute ratios instead of the totals divides by zero in a quiet minute and overweights thin minutes.

    python
    from collections import deque
    
    class Surge:
        def __init__(self, w, cap=3.0):
            self.w, self.cap = w, cap
            self.win, self.req, self.sup = deque(), 0, 0
    
        def add_minute(self, requests, drivers):
            self.win.append((requests, drivers))
            self.req += requests
            self.sup += drivers
            if len(self.win) > self.w:
                r, s = self.win.popleft()
                self.req -= r
                self.sup -= s
            ratio = self.req / max(self.sup, 1)
            return round(min(self.cap, max(1.0, ratio)), 1)
    java
    import java.util.*;
    
    class Surge {
        private final int w;
        private final double cap;
        private final ArrayDeque<int[]> win = new ArrayDeque<>();
        private long req = 0, sup = 0;
        Surge(int w, double cap) { this.w = w; this.cap = cap; }
        double addMinute(int requests, int drivers) {
            win.addLast(new int[]{requests, drivers});
            req += requests;
            sup += drivers;
            if (win.size() > w) { int[] old = win.pollFirst(); req -= old[0]; sup -= old[1]; }
            double ratio = (double) req / Math.max(sup, 1);
            return Math.round(Math.min(cap, Math.max(1.0, ratio)) * 10) / 10.0;
        }
    }
  3. 3

    Fastest travel time between two junctions on a road network with positive travel times.

    medium

    Run Dijkstra's algorithm with a min-heap keyed by the best known time to each junction. Pop the closest, skip it if a better entry was already finalised, and relax its outgoing roads. When the destination is popped its time is final. O((V + E) log V). Dijkstra fails with negative weights, so do not use it for problems that include them. The classic mistake is not skipping stale heap entries, which is correct but slow, and forgetting that two-way roads need an edge in each direction.

    python
    import heapq
    from collections import defaultdict
    
    def fastest(roads, src, dst):                 # roads: (u, v, minutes), one-way
        adj = defaultdict(list)
        for u, v, w in roads:
            adj[u].append((v, w))
        best = {src: 0}
        heap = [(0, src)]
        while heap:
            t, u = heapq.heappop(heap)
            if u == dst:
                return t
            if t > best.get(u, float('inf')):
                continue
            for v, w in adj[u]:
                if t + w < best.get(v, float('inf')):
                    best[v] = t + w
                    heapq.heappush(heap, (t + w, v))
        return -1
    java
    import java.util.*;
    
    static int fastest(int n, int[][] roads, int src, int dst) {
        List<List<int[]>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int[] r : roads) adj.get(r[0]).add(new int[]{r[1], r[2]});
        int[] best = new int[n];
        Arrays.fill(best, Integer.MAX_VALUE);
        best[src] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        pq.add(new int[]{0, src});
        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            if (cur[1] == dst) return cur[0];
            if (cur[0] > best[cur[1]]) continue;
            for (int[] e : adj.get(cur[1]))
                if (cur[0] + e[1] < best[e[0]]) { best[e[0]] = cur[0] + e[1]; pq.add(new int[]{best[e[0]], e[0]}); }
        }
        return -1;
    }
  4. 4

    Can a car with a fixed seat count complete a list of shared trips without ever exceeding capacity?

    medium

    Convert each trip into two events: passengers added at the pickup stop and removed at the drop-off stop. Sort the stops and keep a running occupancy, failing as soon as it exceeds capacity. Because a drop-off and a pickup at the same stop share one event key, they net out, which models passengers leaving before others board. O(t log t) for t trips. Processing pickups before drop-offs at a shared stop rejects trips that are actually fine.

    python
    from collections import defaultdict
    
    def car_pool(trips, capacity):               # trips: (passengers, pickup, dropoff)
        delta = defaultdict(int)
        for n, a, b in trips:
            delta[a] += n
            delta[b] -= n
        load = 0
        for stop in sorted(delta):
            load += delta[stop]
            if load > capacity:
                return False
        return True
    java
    import java.util.*;
    
    static boolean carPool(int[][] trips, int capacity) {
        TreeMap<Integer, Integer> delta = new TreeMap<>();
        for (int[] t : trips) {
            delta.merge(t[1], t[0], Integer::sum);
            delta.merge(t[2], -t[0], Integer::sum);
        }
        int load = 0;
        for (int d : delta.values()) {
            load += d;
            if (load > capacity) return false;
        }
        return true;
    }
  5. 5

    Compute a trip fare with a base for the first 2 km, two per-kilometre slabs and paid waiting time.

    easy

    Work in paise and metres. Charge the flat base for the first 2,000 m, then price the next 8,000 m at the first rate and everything beyond at the second, using ceiling division so a partial kilometre is not undercharged. Add waiting charges only for minutes beyond a free allowance. All arithmetic is constant time. Applying the higher rate to the whole distance, or using floating point for money, are the usual errors; the slab boundaries at exactly 2 km and 10 km are where tests will probe.

    python
    def fare(metres, wait_min):
        total, remaining = 5000, max(0, metres - 2000)          # base covers 2 km
        for width, rate in ((8000, 1200), (None, 1500)):         # paise per km
            part = remaining if width is None else min(remaining, width)
            total += -(-part * rate // 1000)
            remaining -= part
        return total + max(0, wait_min - 3) * 100
    java
    static long fare(long metres, long waitMin) {
        long total = 5000, remaining = Math.max(0, metres - 2000);
        long[][] slabs = {{8000, 1200}, {Long.MAX_VALUE, 1500}};
        for (long[] s : slabs) {
            long part = Math.min(remaining, s[0]);
            total += (part * s[1] + 999) / 1000;
            remaining -= part;
        }
        return total + Math.max(0, waitMin - 3) * 100;
    }
  6. 6

    Choose one pickup point for a group that minimises total Manhattan walking distance.

    medium

    Walking distance splits into independent x and y parts, and the sum of absolute deviations on a line is smallest at the median. So take the median of all x values and the median of all y values, then sum the distances to that point. Sorting gives O(n log n). Using the mean is the tempting error, since the mean minimises squared distance, not absolute distance, and it can be a point nobody would stand on.

    python
    def best_pickup(points):
        xs = sorted(p[0] for p in points)
        ys = sorted(p[1] for p in points)
        mx, my = xs[len(xs) // 2], ys[len(ys) // 2]
        return (mx, my), sum(abs(x - mx) + abs(y - my) for x, y in points)
    java
    import java.util.*;
    
    static long[] bestPickup(int[][] pts) {
        int n = pts.length;
        int[] xs = new int[n], ys = new int[n];
        for (int i = 0; i < n; i++) { xs[i] = pts[i][0]; ys[i] = pts[i][1]; }
        Arrays.sort(xs);
        Arrays.sort(ys);
        long mx = xs[n / 2], my = ys[n / 2], cost = 0;
        for (int[] p : pts) cost += Math.abs(p[0] - mx) + Math.abs(p[1] - my);
        return new long[]{mx, my, cost};
    }
  7. 7

    Machine coding: find the nearest available driver using a grid of city cells.

    hard

    Divide the map into square cells and keep a set of driver ids per cell plus each driver's current location. An update removes the driver from the old cell and inserts into the new one. To match, scan the rider's own cell, then rings of cells outward, tracking the best distance; once a finished ring r has a candidate no farther than r times the cell size, no unscanned cell can beat it, so stop. Average cost is far below scanning every driver. Forgetting to delete a driver from the old cell leaves ghost drivers.

    python
    from collections import defaultdict
    
    class Dispatch:
        def __init__(self, cell=1000):
            self.cell, self.cells, self.loc = cell, defaultdict(set), {}
    
        def _c(self, x, y):
            return (x // self.cell, y // self.cell)
    
        def update(self, driver, x, y):
            if driver in self.loc:
                self.cells[self._c(*self.loc[driver])].discard(driver)
            self.loc[driver] = (x, y)
            self.cells[self._c(x, y)].add(driver)
    
        def nearest(self, x, y, max_ring=5):
            cx, cy = self._c(x, y)
            best = None
            for r in range(max_ring + 1):
                for dx in range(-r, r + 1):
                    for dy in range(-r, r + 1):
                        if max(abs(dx), abs(dy)) != r:
                            continue
                        for d in self.cells.get((cx + dx, cy + dy), ()):
                            lx, ly = self.loc[d]
                            cand = ((lx - x) ** 2 + (ly - y) ** 2, d)
                            if best is None or cand < best:
                                best = cand
                if best and best[0] <= (r * self.cell) ** 2:
                    break
            return best[1] if best else None
    java
    import java.util.*;
    
    class Dispatch {
        private final int cell;
        private final Map<Long, Set<Integer>> cells = new HashMap<>();
        private final Map<Integer, int[]> loc = new HashMap<>();
        Dispatch(int cell) { this.cell = cell; }
        private long key(int cx, int cy) { return cx * 1_000_003L + cy; }
        private int c(int v) { return Math.floorDiv(v, cell); }
        void update(int driver, int x, int y) {
            int[] old = loc.get(driver);
            if (old != null) cells.get(key(c(old[0]), c(old[1]))).remove(driver);
            loc.put(driver, new int[]{x, y});
            cells.computeIfAbsent(key(c(x), c(y)), k -> new HashSet<>()).add(driver);
        }
        Integer nearest(int x, int y, int maxRing) {
            int cx = c(x), cy = c(y);
            long bestD = Long.MAX_VALUE;
            Integer best = null;
            for (int r = 0; r <= maxRing; r++) {
                for (int dx = -r; dx <= r; dx++)
                    for (int dy = -r; dy <= r; dy++) {
                        if (Math.max(Math.abs(dx), Math.abs(dy)) != r) continue;
                        for (int d : cells.getOrDefault(key(cx + dx, cy + dy), Set.of())) {
                            int[] l = loc.get(d);
                            long dd = (long) (l[0] - x) * (l[0] - x) + (long) (l[1] - y) * (l[1] - y);
                            if (dd < bestD || (dd == bestD && d < best)) { bestD = dd; best = d; }
                        }
                    }
                if (best != null && bestD <= (long) r * cell * r * cell) break;
            }
            return best;
        }
    }
  8. 8

    How many minutes until a surge in demand has spread to every reachable zone on a grid?

    medium

    Cells hold 2 for a surging zone, 1 for a normal zone and 0 for no service area. Every minute each surging zone infects its four neighbours that are normal. Start a multi-source breadth-first search with all surging zones in the queue at once, process level by level, and count levels. If any normal zone is untouched at the end return -1. O(rows x cols). Starting a separate search from each surging zone, or counting minutes per queue pop instead of per level, gives the wrong time.

    python
    from collections import deque
    
    def surge_minutes(grid):
        R, C = len(grid), len(grid[0])
        q = deque((r, c) for r in range(R) for c in range(C) if grid[r][c] == 2)
        normal = sum(row.count(1) for row in grid)
        minutes = 0
        while q and normal:
            for _ in range(len(q)):
                r, c = q.popleft()
                for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 1:
                        grid[nr][nc] = 2
                        normal -= 1
                        q.append((nr, nc))
            minutes += 1
        return minutes if normal == 0 else -1
    java
    import java.util.*;
    
    static int surgeMinutes(int[][] g) {
        int R = g.length, C = g[0].length, normal = 0, minutes = 0;
        ArrayDeque<int[]> q = new ArrayDeque<>();
        for (int r = 0; r < R; r++)
            for (int c = 0; c < C; c++) {
                if (g[r][c] == 2) q.add(new int[]{r, c});
                else if (g[r][c] == 1) normal++;
            }
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!q.isEmpty() && normal > 0) {
            for (int s = q.size(); s > 0; s--) {
                int[] cur = q.poll();
                for (int[] d : dirs) {
                    int nr = cur[0] + d[0], nc = cur[1] + d[1];
                    if (nr >= 0 && nr < R && nc >= 0 && nc < C && g[nr][nc] == 1) {
                        g[nr][nc] = 2;
                        normal--;
                        q.add(new int[]{nr, nc});
                    }
                }
            }
            minutes++;
        }
        return normal == 0 ? minutes : -1;
    }
  9. 9

    Charging stops arranged in a ring: find a starting stop from which an electric cab can complete the loop.

    medium

    Each stop gives some range gained and each leg costs some range. If total gain is less than total cost, no start works. Otherwise sweep once with a running tank; whenever it goes negative, no start at or before that stop can work, so reset the tank and make the next stop the candidate. The candidate left at the end is valid. O(n) time, O(1) space. Trying every start is O(n squared), and forgetting the total-gain check can return an index when the loop is impossible.

    python
    def start_stop(gain, cost):
        if sum(gain) < sum(cost):
            return -1
        tank = start = 0
        for i in range(len(gain)):
            tank += gain[i] - cost[i]
            if tank < 0:
                start, tank = i + 1, 0
        return start
    java
    static int startStop(int[] gain, int[] cost) {
        int total = 0, tank = 0, start = 0;
        for (int i = 0; i < gain.length; i++) {
            int diff = gain[i] - cost[i];
            total += diff;
            tank += diff;
            if (tank < 0) { start = i + 1; tank = 0; }
        }
        return total < 0 ? -1 : start;
    }
  10. 10

    Cheapest way to cover a driver's list of working days with one-day, seven-day and thirty-day permits.

    medium

    Let dp[d] be the cheapest cost to cover all travel days up to day d. On a non-travel day it equals the previous day's value. On a travel day take the best of buying a one-day permit after day d-1, a seven-day permit that started at d-6, or a thirty-day permit that started at d-29, clamping indexes at zero. O(last day). Greedy by cheapest per-day rate fails, because a long permit bought early can waste days while a short one gets you to the next gap cheaper.

    python
    def min_permit_cost(days, costs):
        if not days:
            return 0
        travel, last = set(days), max(days)
        dp = [0] * (last + 1)
        for d in range(1, last + 1):
            if d not in travel:
                dp[d] = dp[d - 1]
            else:
                dp[d] = min(dp[d - 1] + costs[0],
                            dp[max(0, d - 7)] + costs[1],
                            dp[max(0, d - 30)] + costs[2])
        return dp[last]
    java
    static int minPermitCost(int[] days, int[] costs) {
        if (days.length == 0) return 0;
        int last = 0;
        for (int d : days) last = Math.max(last, d);
        boolean[] travel = new boolean[last + 1];
        for (int d : days) travel[d] = true;
        int[] dp = new int[last + 1];
        for (int d = 1; d <= last; d++) {
            if (!travel[d]) { dp[d] = dp[d - 1]; continue; }
            dp[d] = Math.min(dp[d - 1] + costs[0],
                    Math.min(dp[Math.max(0, d - 7)] + costs[1], dp[Math.max(0, d - 30)] + costs[2]));
        }
        return dp[last];
    }

Frequently asked questions

Are Ola's coding rounds really about maps and routes?

Only a small sample of candidate reports exists, so do not assume it. Graph and heap problems are common across product companies anyway, which is why they dominate this set.

When should I choose BFS over Dijkstra?

Use breadth-first search when every step costs the same, such as moving between grid cells. Use Dijkstra when edges carry different non-negative costs, such as travel minutes between junctions.

Why is money kept as integers in fare problems?

Floating-point values cannot represent most decimal amounts exactly, so totals drift. Paise in a long integer, with explicit ceiling or rounding rules, keeps every rupee accounted for.

How do I explain a heap-based solution to an interviewer?

Say what the heap holds, what ordering it uses, and why the top element is the one you need next. Then give the cost per push and pop. That is usually enough to convince.

Sources

Related guides

More in Company Interview Questions

See all in this section