Autocoder

Uber Coding Round Questions with Solutions in Python and Java

Last updated 2026-11-19

Uber's coding interviews favour practical problems and working code. Given its maps, trips and logs, these ten problems cover shortest paths, hop-limited routes, sliding windows, streaming medians, topological ordering, Euler paths and log processing.

Solve each yourself first, then compare with the worked Python and Java solutions, which include complexity and the mistakes to avoid.

Problems10, medium to hard
LanguagesPython and Java
PatternsDijkstra, BFS, heaps, monotonic deque, topological sort
Style, per UberPractical problems, working code

What Uber-style problems look like

Uber's engineering interview post says coding interviews use practical problems rather than puzzles and look at how you turn your thinking into working code. For a company built on maps, marketplaces and event logs, practical problems naturally involve graphs and shortest paths, streams and windows, scheduling and logs. The ten problems below follow those themes and are practice problems, not real interview content.

For system design and behavioural preparation see Uber interview questions and the graph interview questions guide.

Mistakes in graph and stream problems

Hiring status

For current Uber roles, see Uber hiring and apply through uber.com/in/en/careers. Uber was reported in May 2026 to be planning new Bengaluru and Hyderabad campuses opening by the end of 2027, with no role-level hiring numbers given.

Uber Coding Round Questions with Solutions in Python and Java: questions with worked answers

  1. 1

    Network Delay Time: time for a signal to reach all nodes in a directed weighted graph.

    medium

    Run Dijkstra from the source with a min-heap; the answer is the largest shortest distance, or -1 if some node is unreachable. Time O(E log V), space O(V + E). Mistake: using BFS on a weighted graph, or returning the sum of distances rather than the maximum.

    python
    import heapq
    def network_delay(times, n, k):
        adj = {i: [] for i in range(1, n + 1)}
        for u, v, w in times: adj[u].append((v, w))
        dist, h = {}, [(0, k)]
        while h:
            d, u = heapq.heappop(h)
            if u in dist: continue
            dist[u] = d
            for v, w in adj[u]:
                if v not in dist: heapq.heappush(h, (d + w, v))
        return max(dist.values()) if len(dist) == n else -1
    java
    import java.util.*;
    class Solution {
        int networkDelay(int[][] times, int n, int k) {
            List<int[]>[] adj = new List[n + 1];
            for (int i = 0; i <= n; i++) adj[i] = new ArrayList<>();
            for (int[] t : times) adj[t[0]].add(new int[]{t[1], t[2]});
            int[] dist = new int[n + 1];
            Arrays.fill(dist, Integer.MAX_VALUE);
            PriorityQueue<int[]> h = new PriorityQueue<>((a, b) -> a[0] - b[0]);
            h.add(new int[]{0, k});
            while (!h.isEmpty()) {
                int[] c = h.poll();
                if (c[0] >= dist[c[1]]) continue;
                dist[c[1]] = c[0];
                for (int[] e : adj[c[1]]) if (c[0] + e[1] < dist[e[0]]) h.add(new int[]{c[0] + e[1], e[0]});
            }
            int best = 0;
            for (int i = 1; i <= n; i++) { if (dist[i] == Integer.MAX_VALUE) return -1; best = Math.max(best, dist[i]); }
            return best;
        }
    }
  2. 2

    Cheapest Flights Within K Stops.

    medium

    Bellman-Ford limited to k + 1 edges: repeat k + 1 times, relaxing every flight using a copy of the previous round's distances so a round adds at most one edge. Time O(k x E), space O(V). Mistake: relaxing in place, which can use more than k + 1 edges in a single round, or using plain Dijkstra that ignores the stop limit.

    python
    def cheapest(n, flights, src, dst, k):
        INF = float('inf')
        dist = [INF] * n
        dist[src] = 0
        for _ in range(k + 1):
            nxt = dist[:]
            for u, v, w in flights:
                if dist[u] + w < nxt[v]: nxt[v] = dist[u] + w
            dist = nxt
        return -1 if dist[dst] == INF else dist[dst]
    java
    import java.util.*;
    class Solution {
        int cheapest(int n, int[][] flights, int src, int dst, int k) {
            int INF = Integer.MAX_VALUE / 2;
            int[] dist = new int[n];
            Arrays.fill(dist, INF);
            dist[src] = 0;
            for (int i = 0; i <= k; i++) {
                int[] nxt = dist.clone();
                for (int[] f : flights) if (dist[f[0]] + f[2] < nxt[f[1]]) nxt[f[1]] = dist[f[0]] + f[2];
                dist = nxt;
            }
            return dist[dst] >= INF ? -1 : dist[dst];
        }
    }
  3. 3

    Car Fleet: how many fleets arrive at the destination.

    medium

    Sort cars by starting position descending; compute each car's time to reach the target. Iterate from the car nearest the target: if a car's time is greater than the fleet ahead of it, it forms a new fleet, otherwise it catches up and joins. Time O(n log n), space O(n). Mistake: processing from the farthest car and comparing in the wrong direction.

    python
    def car_fleet(target, pos, speed):
        fleets, last = 0, 0.0
        for p, s in sorted(zip(pos, speed), reverse=True):
            t = (target - p) / s
            if t > last:
                fleets += 1; last = t
        return fleets
    java
    import java.util.*;
    class Solution {
        int carFleet(int target, int[] pos, int[] speed) {
            int n = pos.length;
            Integer[] idx = new Integer[n];
            for (int i = 0; i < n; i++) idx[i] = i;
            Arrays.sort(idx, (a, b) -> pos[b] - pos[a]);
            int fleets = 0; double last = 0;
            for (int i : idx) {
                double t = (double) (target - pos[i]) / speed[i];
                if (t > last) { fleets++; last = t; }
            }
            return fleets;
        }
    }
  4. 4

    Sliding Window Maximum.

    hard

    Use a monotonic decreasing deque of indices. For each new element pop smaller values from the back, push the index, drop the front if it left the window, and the front is the maximum. Each index enters and leaves once: time O(n), space O(k). Mistake: recomputing max(window) each step, which is O(n k), or storing values instead of indices so you cannot expire them.

    python
    from collections import deque
    def max_sliding_window(a, k):
        dq, out = deque(), []
        for i, x in enumerate(a):
            while dq and a[dq[-1]] <= x: dq.pop()
            dq.append(i)
            if dq[0] <= i - k: dq.popleft()
            if i >= k - 1: out.append(a[dq[0]])
        return out
    java
    import java.util.*;
    class Solution {
        int[] maxSlidingWindow(int[] a, int k) {
            Deque<Integer> dq = new ArrayDeque<>();
            int[] out = new int[a.length - k + 1];
            for (int i = 0; i < a.length; i++) {
                while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) dq.pollLast();
                dq.addLast(i);
                if (dq.peekFirst() <= i - k) dq.pollFirst();
                if (i >= k - 1) out[i - k + 1] = a[dq.peekFirst()];
            }
            return out;
        }
    }
  5. 5

    Find Median from a Data Stream.

    hard

    Keep two heaps: a max-heap for the smaller half and a min-heap for the larger half, balanced so their sizes differ by at most one. Insert into the max-heap, move its top to the min-heap, and rebalance. The median is the top of the larger heap, or the mean of the two tops. Insert O(log n), median O(1). Mistake: sorting the list for every query.

    python
    import heapq
    class MedianFinder:
        def __init__(self):
            self.lo, self.hi = [], []   # lo is a max-heap via negatives
        def add_num(self, x):
            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):
            if len(self.lo) > len(self.hi): return float(-self.lo[0])
            return (-self.lo[0] + self.hi[0]) / 2
    java
    import java.util.*;
    class MedianFinder {
        private final PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder()), hi = new PriorityQueue<>();
        void addNum(int x) {
            lo.add(x); hi.add(lo.poll());
            if (hi.size() > lo.size()) lo.add(hi.poll());
        }
        double findMedian() {
            return lo.size() > hi.size() ? lo.peek() : ((double) lo.peek() + hi.peek()) / 2;
        }
    }
  6. 6

    Alien Dictionary: derive letter order from a sorted list of alien words.

    hard

    Compare adjacent words to find the first differing letter, which gives an edge a before b, then topologically sort the letters. If a longer word precedes its own prefix, the input is invalid, and a cycle means no valid order. Time O(total characters + edges). Mistake: forgetting letters that never appear in an edge, and missing the prefix case.

    python
    from collections import deque
    def alien_order(words):
        adj = {c: set() for w in words for c in w}
        deg = {c: 0 for c in adj}
        for a, b in zip(words, words[1:]):
            if len(a) > len(b) and a.startswith(b): return ""
            for x, y in zip(a, b):
                if x != y:
                    if y not in adj[x]: adj[x].add(y); deg[y] += 1
                    break
        q = deque(c for c in deg if deg[c] == 0); out = []
        while q:
            c = q.popleft(); out.append(c)
            for n in adj[c]:
                deg[n] -= 1
                if deg[n] == 0: q.append(n)
        return ''.join(out) if len(out) == len(adj) else ""
    java
    import java.util.*;
    class Solution {
        String alienOrder(String[] words) {
            Map<Character, Set<Character>> adj = new HashMap<>();
            Map<Character, Integer> deg = new HashMap<>();
            for (String w : words) for (char c : w.toCharArray()) { adj.putIfAbsent(c, new HashSet<>()); deg.putIfAbsent(c, 0); }
            for (int i = 0; i + 1 < words.length; i++) {
                String a = words[i], b = words[i + 1];
                if (a.length() > b.length() && a.startsWith(b)) return "";
                for (int j = 0; j < Math.min(a.length(), b.length()); j++)
                    if (a.charAt(j) != b.charAt(j)) {
                        if (adj.get(a.charAt(j)).add(b.charAt(j))) deg.merge(b.charAt(j), 1, Integer::sum);
                        break;
                    }
            }
            Deque<Character> q = new ArrayDeque<>();
            for (var e : deg.entrySet()) if (e.getValue() == 0) q.add(e.getKey());
            StringBuilder sb = new StringBuilder();
            while (!q.isEmpty()) {
                char c = q.poll(); sb.append(c);
                for (char n : adj.get(c)) if (deg.merge(n, -1, Integer::sum) == 0) q.add(n);
            }
            return sb.length() == adj.size() ? sb.toString() : "";
        }
    }
  7. 7

    Shortest Path in a Binary Matrix from top-left to bottom-right through zeros, moving in 8 directions.

    medium

    BFS from the start cell, where the answer is the number of cells on the path, and mark cells visited when you enqueue them. Return -1 if the start or end is blocked. Time and space O(n squared) for an n by n grid. Mistake: DFS, which does not give the shortest path, or only allowing four directions when the problem permits diagonals.

    python
    from collections import deque
    def shortest_path(g):
        n = len(g)
        if g[0][0] or g[n-1][n-1]: return -1
        q, g[0][0] = deque([(0, 0, 1)]), 1
        while q:
            x, y, d = q.popleft()
            if x == y == n - 1: return d
            for dx in (-1, 0, 1):
                for dy in (-1, 0, 1):
                    a, b = x + dx, y + dy
                    if 0 <= a < n and 0 <= b < n and g[a][b] == 0:
                        g[a][b] = 1; q.append((a, b, d + 1))
        return -1
    java
    import java.util.*;
    class Solution {
        int shortestPath(int[][] g) {
            int n = g.length;
            if (g[0][0] == 1 || g[n-1][n-1] == 1) return -1;
            Deque<int[]> q = new ArrayDeque<>();
            q.add(new int[]{0, 0, 1}); g[0][0] = 1;
            while (!q.isEmpty()) {
                int[] c = q.poll();
                if (c[0] == n - 1 && c[1] == n - 1) return c[2];
                for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) {
                    int a = c[0] + dx, b = c[1] + dy;
                    if (a >= 0 && b >= 0 && a < n && b < n && g[a][b] == 0) { g[a][b] = 1; q.add(new int[]{a, b, c[2] + 1}); }
                }
            }
            return -1;
        }
    }
  8. 8

    Reconstruct Itinerary: use all tickets once, starting at JFK, lexicographically smallest.

    hard

    This asks for an Eulerian path. Store destinations per airport in a min-heap, and run Hierholzer's algorithm: DFS taking the smallest destination, appending an airport to the route only when it has no outgoing tickets left, then reverse the route. Time O(E log E). Mistake: plain DFS that picks the smallest next city and gets stuck at a dead end before using all tickets.

    python
    import heapq
    from collections import defaultdict
    def find_itinerary(tickets):
        g = defaultdict(list)
        for a, b in tickets: heapq.heappush(g[a], b)
        route = []
        def dfs(a):
            while g[a]:
                dfs(heapq.heappop(g[a]))
            route.append(a)
        dfs('JFK')
        return route[::-1]
    java
    import java.util.*;
    class Solution {
        private final Map<String, PriorityQueue<String>> g = new HashMap<>();
        private final LinkedList<String> route = new LinkedList<>();
        List<String> findItinerary(List<List<String>> tickets) {
            for (List<String> t : tickets) g.computeIfAbsent(t.get(0), k -> new PriorityQueue<>()).add(t.get(1));
            dfs("JFK");
            return route;
        }
        private void dfs(String a) {
            PriorityQueue<String> q = g.get(a);
            while (q != null && !q.isEmpty()) dfs(q.poll());
            route.addFirst(a);
        }
    }
  9. 9

    Minimum Number of Refueling Stops to reach a target distance.

    hard

    Greedy with a max-heap: drive as far as the fuel allows, pushing the fuel amounts of all stations passed into a max-heap; when you cannot reach the next point, refuel with the largest station you have passed (pop the heap), counting a stop. If the heap is empty when stuck, return -1. Time O(n log n). Mistake: refuelling at every station, or choosing the nearest station rather than the biggest tank passed.

    python
    import heapq
    def min_refuel(target, start_fuel, stations):
        h, fuel, stops, i = [], start_fuel, 0, 0
        stations = stations + [[target, 0]]
        pos = 0
        for p, f in stations:
            fuel -= p - pos; pos = p
            while fuel < 0 and h:
                fuel += -heapq.heappop(h); stops += 1
            if fuel < 0: return -1
            heapq.heappush(h, -f)
        return stops
    java
    import java.util.*;
    class Solution {
        int minRefuel(int target, int startFuel, int[][] stations) {
            PriorityQueue<Integer> h = new PriorityQueue<>(Collections.reverseOrder());
            int fuel = startFuel, stops = 0, pos = 0;
            for (int i = 0; i <= stations.length; i++) {
                int p = i < stations.length ? stations[i][0] : target;
                int f = i < stations.length ? stations[i][1] : 0;
                fuel -= p - pos; pos = p;
                while (fuel < 0 && !h.isEmpty()) { fuel += h.poll(); stops++; }
                if (fuel < 0) return -1;
                h.add(f);
            }
            return stops;
        }
    }
  10. 10

    Exclusive Time of Functions from start and end logs.

    medium

    Use a stack of function ids and track the previous timestamp. On a start log, credit the elapsed time since the previous timestamp to the function on top (if any), push the new id and update the timestamp. On an end log, credit elapsed time plus one to the top function, pop, and set the previous timestamp to end + 1. Time O(n). Mistake: not treating the end timestamp as inclusive.

    python
    def exclusive_time(n, logs):
        res, st, prev = [0] * n, [], 0
        for log in logs:
            fid, kind, t = log.split(':')
            fid, t = int(fid), int(t)
            if kind == 'start':
                if st: res[st[-1]] += t - prev
                st.append(fid); prev = t
            else:
                res[st.pop()] += t - prev + 1
                prev = t + 1
        return res
    java
    import java.util.*;
    class Solution {
        int[] exclusiveTime(int n, List<String> logs) {
            int[] res = new int[n];
            Deque<Integer> st = new ArrayDeque<>();
            int prev = 0;
            for (String log : logs) {
                String[] p = log.split(":");
                int id = Integer.parseInt(p[0]), t = Integer.parseInt(p[2]);
                if (p[1].equals("start")) {
                    if (!st.isEmpty()) res[st.peek()] += t - prev;
                    st.push(id); prev = t;
                } else {
                    res[st.pop()] += t - prev + 1;
                    prev = t + 1;
                }
            }
            return res;
        }
    }

Frequently asked questions

Are Uber coding problems hard?

Commonly practised at medium to hard difficulty, especially graph and heap problems, with emphasis on working code.

Which language should I use?

Use the one you code fastest in. Python and Java are both given for every problem here.

Do Uber interviews include graphs?

Given its maps and marketplace, graph shortest-path and ordering problems are common practice. They are not guaranteed in any interview.

Sources

Related guides

More in Company Interview Questions

See all in this section