Autocoder

Amazon Coding Round Questions with Solutions in Python and Java

Last updated 2026-11-19

Amazon's coding assessment is made of practical problems with strict hidden tests. These ten cover the patterns that come up most often: hash maps, heaps, BFS on grids, interval scheduling and caches.

Try each one against the clock before reading the solution. Python and Java versions are given with complexity and the mistakes to avoid.

Problems10, easy to medium-hard
LanguagesPython and Java
PatternsHeaps, BFS, hash maps, intervals, caches
Assessment styleTimed, hidden test cases

What Amazon's assessment looks like

Amazon describes the SDE II assessment as two coding questions in 90 minutes plus system design scenarios and a work style survey, and the university assessment as roughly 70 minutes of coding plus other sections. It also says browser activity is logged and public documentation is allowed in the coding section. The problems below match the style: practical array, string, graph and heap problems with hidden test cases that reward edge-case care.

These are practice problems, not real test content. For the behavioural side see Amazon interview questions.

Mistakes that cost the most marks

Hiring status

For current Amazon roles and dates, see Amazon hiring. Amazon lists an SDE I Intern role for 2027 graduates with start dates between January and June 2027 on amazon.jobs, which is the place to apply.

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

  1. 1

    Two Sum: indices of two numbers adding to a target.

    easy

    Store each value's index in a hash map; for each number check whether target minus it is already there. One pass, time O(n), space O(n). Mistake: using the same element twice, which the map-then-check order avoids. Sorting and two pointers works in O(n log n) but loses original indices unless you keep them.

    python
    def two_sum(a, t):
        seen = {}
        for i, x in enumerate(a):
            if t - x in seen: return [seen[t - x], i]
            seen[x] = i
        return []
    java
    import java.util.*;
    class Solution {
        int[] twoSum(int[] a, int t) {
            Map<Integer, Integer> m = new HashMap<>();
            for (int i = 0; i < a.length; i++) {
                Integer j = m.get(t - a[i]);
                if (j != null) return new int[]{j, i};
                m.put(a[i], i);
            }
            return new int[0];
        }
    }
  2. 2

    Rotting Oranges: minutes until all oranges rot (0 empty, 1 fresh, 2 rotten), or -1.

    medium

    Multi-source BFS: queue every rotten orange at time zero, then spread level by level, counting each level as a minute and tracking the number of fresh oranges left. Time and space O(rows x cols). Mistakes: running BFS from each rotten orange separately, counting one extra minute after the last level, and forgetting to return -1 when fresh oranges remain.

    python
    from collections import deque
    def oranges_rotting(g):
        R, C = len(g), len(g[0])
        q = deque((i, j) for i in range(R) for j in range(C) if g[i][j] == 2)
        fresh = sum(row.count(1) for row in g)
        mins = 0
        while q and fresh:
            for _ in range(len(q)):
                x, y = q.popleft()
                for a, b in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):
                    if 0 <= a < R and 0 <= b < C and g[a][b] == 1:
                        g[a][b] = 2; fresh -= 1; q.append((a, b))
            mins += 1
        return -1 if fresh else mins
    java
    import java.util.*;
    class Solution {
        int orangesRotting(int[][] g) {
            int R = g.length, C = g[0].length, fresh = 0, mins = 0;
            Deque<int[]> q = new ArrayDeque<>();
            for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) {
                if (g[i][j] == 2) q.add(new int[]{i, j}); else if (g[i][j] == 1) fresh++;
            }
            int[][] d = {{1,0},{-1,0},{0,1},{0,-1}};
            while (!q.isEmpty() && fresh > 0) {
                for (int s = q.size(); s > 0; s--) {
                    int[] p = q.poll();
                    for (int[] v : d) {
                        int a = p[0] + v[0], b = p[1] + v[1];
                        if (a >= 0 && a < R && b >= 0 && b < C && g[a][b] == 1) { g[a][b] = 2; fresh--; q.add(new int[]{a, b}); }
                    }
                }
                mins++;
            }
            return fresh > 0 ? -1 : mins;
        }
    }
  3. 3

    Reorder Data in Log Files: letter-logs first sorted by content then identifier, digit-logs keep order.

    medium

    Split each log into identifier and body. A log is a digit-log if the first character of its body is a digit. Sort letter-logs by (body, identifier) and append the digit-logs in original order. Time O(n log n x m) for log length m. Mistake: sorting digit-logs too (they must stay stable) or comparing the whole line instead of body then identifier.

    python
    def reorder(logs):
        letters, digits = [], []
        for l in logs:
            ident, body = l.split(' ', 1)
            (digits if body[0].isdigit() else letters).append((body, ident, l))
        letters.sort()
        return [l for _, _, l in letters] + [l for _, _, l in digits]
    java
    import java.util.*;
    class Solution {
        String[] reorder(String[] logs) {
            List<String> letters = new ArrayList<>(), digits = new ArrayList<>();
            for (String l : logs) {
                String body = l.substring(l.indexOf(' ') + 1);
                if (Character.isDigit(body.charAt(0))) digits.add(l); else letters.add(l);
            }
            letters.sort((a, b) -> {
                String ba = a.substring(a.indexOf(' ') + 1), bb = b.substring(b.indexOf(' ') + 1);
                int c = ba.compareTo(bb);
                return c != 0 ? c : a.substring(0, a.indexOf(' ')).compareTo(b.substring(0, b.indexOf(' ')));
            });
            letters.addAll(digits);
            return letters.toArray(new String[0]);
        }
    }
  4. 4

    Merge k Sorted Lists.

    hard

    Put the head of each list in a min-heap keyed by value; repeatedly pop the smallest, append it, and push its successor. With N total nodes and k lists, time is O(N log k) and extra space O(k). Mistakes: comparing ListNode objects directly in Python (add an index as a tie-breaker) and merging lists one after another, which is O(N k).

    python
    import heapq
    def merge_k(lists):
        h = [(n.val, i, n) for i, n in enumerate(lists) if n]
        heapq.heapify(h)
        dummy = tail = ListNode(0)
        while h:
            _, i, n = heapq.heappop(h)
            tail.next = n; tail = n
            if n.next: heapq.heappush(h, (n.next.val, i, n.next))
        return dummy.next
    java
    import java.util.*;
    class ListNode { int val; ListNode next; ListNode(int v) { val = v; } }
    class Solution {
        ListNode mergeK(ListNode[] lists) {
            PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
            for (ListNode n : lists) if (n != null) pq.add(n);
            ListNode dummy = new ListNode(0), tail = dummy;
            while (!pq.isEmpty()) {
                ListNode n = pq.poll();
                tail.next = n; tail = n;
                if (n.next != null) pq.add(n.next);
            }
            return dummy.next;
        }
    }
  5. 5

    Minimum Cost to Connect Sticks (ropes): join all sticks, each join costs the sum of the two lengths.

    medium

    Greedy with a min-heap: always join the two shortest sticks, push the result back, and add its length to the total. This is Huffman-style merging, so shorter sticks get re-counted the most times. Time O(n log n), space O(n). Mistake: sorting once and joining left to right, which ignores that the merged stick may now be longer than the next ones.

    python
    import heapq
    def connect(sticks):
        heapq.heapify(sticks)
        cost = 0
        while len(sticks) > 1:
            s = heapq.heappop(sticks) + heapq.heappop(sticks)
            cost += s
            heapq.heappush(sticks, s)
        return cost
    java
    import java.util.*;
    class Solution {
        int connect(int[] sticks) {
            PriorityQueue<Integer> pq = new PriorityQueue<>();
            for (int s : sticks) pq.add(s);
            int cost = 0;
            while (pq.size() > 1) {
                int s = pq.poll() + pq.poll();
                cost += s; pq.add(s);
            }
            return cost;
        }
    }
  6. 6

    Product of Array Except Self without division.

    medium

    Make two passes. First, store in result[i] the product of everything to the left of i. Second, sweep from the right keeping a running product of everything to the right and multiply it in. Time O(n), extra space O(1) beyond the output. Mistake: dividing by the total, which fails with zeros and is banned in the problem.

    python
    def product_except_self(a):
        n = len(a); out = [1] * n
        for i in range(1, n): out[i] = out[i-1] * a[i-1]
        r = 1
        for i in range(n - 1, -1, -1):
            out[i] *= r; r *= a[i]
        return out
    java
    class Solution {
        int[] productExceptSelf(int[] a) {
            int n = a.length; int[] out = new int[n];
            out[0] = 1;
            for (int i = 1; i < n; i++) out[i] = out[i - 1] * a[i - 1];
            int r = 1;
            for (int i = n - 1; i >= 0; i--) { out[i] *= r; r *= a[i]; }
            return out;
        }
    }
  7. 7

    Partition Labels: split a string so each letter appears in at most one part; return part sizes.

    medium

    Record the last index of each letter. Sweep, extending the current part's end to the maximum last index of letters seen; when the index reaches that end, cut a part. Time O(n), space O(1) for 26 letters. Mistake: cutting as soon as the current letter's last occurrence passes, without considering earlier letters in the part.

    python
    def partition_labels(s):
        last = {c: i for i, c in enumerate(s)}
        out, start, end = [], 0, 0
        for i, c in enumerate(s):
            end = max(end, last[c])
            if i == end:
                out.append(end - start + 1); start = i + 1
        return out
    java
    import java.util.*;
    class Solution {
        List<Integer> partitionLabels(String s) {
            int[] last = new int[26];
            for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;
            List<Integer> out = new ArrayList<>();
            int start = 0, end = 0;
            for (int i = 0; i < s.length(); i++) {
                end = Math.max(end, last[s.charAt(i) - 'a']);
                if (i == end) { out.add(end - start + 1); start = i + 1; }
            }
            return out;
        }
    }
  8. 8

    Longest Palindromic Substring.

    medium

    Expand around each of the 2n-1 centres (each character and each gap between characters) while the ends match, tracking the best range. Time O(n squared), space O(1). Manacher's algorithm reaches O(n) but is rarely expected. Mistake: handling only odd-length palindromes, so 'abba' is missed.

    python
    def longest_pal(s):
        best = (0, 0)
        for c in range(len(s)):
            for l, r in ((c, c), (c, c + 1)):
                while l >= 0 and r < len(s) and s[l] == s[r]:
                    l -= 1; r += 1
                if r - l - 1 > best[1] - best[0]: best = (l + 1, r)
        return s[best[0]:best[1]]
    java
    class Solution {
        String longestPal(String s) {
            int bs = 0, be = 0;
            for (int c = 0; c < s.length(); c++)
                for (int k = 0; k < 2; k++) {
                    int l = c, r = c + k;
                    while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }
                    if (r - l - 1 > be - bs) { bs = l + 1; be = r; }
                }
            return s.substring(bs, be);
        }
    }
  9. 9

    Meeting Rooms II: minimum rooms needed for a set of meetings.

    medium

    Sort meetings by start time and keep a min-heap of end times for rooms in use. For each meeting, if the earliest end time is at or before its start, reuse that room (pop it); push the new end time. The heap size at the end is the answer. Time O(n log n), space O(n). Mistake: using strict less-than so back-to-back meetings wrongly need two rooms.

    python
    import heapq
    def min_rooms(iv):
        iv.sort()
        h = []
        for s, e in iv:
            if h and h[0] <= s: heapq.heappop(h)
            heapq.heappush(h, e)
        return len(h)
    java
    import java.util.*;
    class Solution {
        int minRooms(int[][] iv) {
            Arrays.sort(iv, (a, b) -> Integer.compare(a[0], b[0]));
            PriorityQueue<Integer> h = new PriorityQueue<>();
            for (int[] m : iv) {
                if (!h.isEmpty() && h.peek() <= m[0]) h.poll();
                h.add(m[1]);
            }
            return h.size();
        }
    }
  10. 10

    LRU Cache: implement get and put in O(1).

    medium

    Hash map plus recency order. OrderedDict (Python) and an access-ordered LinkedHashMap (Java) give this in a few lines; be prepared to write the doubly linked list version by hand if asked. Both operations O(1), space O(capacity). Mistake: not refreshing recency on put for an existing key, or evicting before inserting when capacity is full and the key already exists.

    python
    from collections import OrderedDict
    class LRUCache:
        def __init__(self, cap):
            self.cap, self.d = cap, OrderedDict()
        def get(self, k):
            if k not in self.d: return -1
            self.d.move_to_end(k)
            return self.d[k]
        def put(self, k, v):
            self.d[k] = v
            self.d.move_to_end(k)
            if len(self.d) > self.cap:
                self.d.popitem(last=False)
    java
    import java.util.*;
    class LRUCache extends LinkedHashMap<Integer, Integer> {
        private final int cap;
        LRUCache(int cap) { super(16, 0.75f, true); this.cap = cap; }
        int getOrDefault(int k) { return super.getOrDefault(k, -1); }
        @Override protected boolean removeEldestEntry(Map.Entry<Integer, Integer> e) { return size() > cap; }
    }

Frequently asked questions

How many coding questions are in the Amazon online assessment?

Amazon's SDE II page describes two coding questions in 90 minutes. University and internship formats differ, so check your invitation.

Which topics should I prioritise for Amazon coding?

Arrays, strings, hash maps, heaps, graph traversal on grids and interval problems cover most practical questions. Add dynamic programming for harder variants.

Can I use the language documentation during the test?

Amazon says publicly accessible resources such as language documentation are allowed in the coding section. Rules can change, so read your test instructions.

Sources

Related guides

More in Company Interview Questions

See all in this section