Autocoder

Apple Coding Round Questions with Solutions in Python and Java

Last updated 2026-11-19

Apple coding interviews tend to use clean, medium-level problems where the follow-up asks about memory or an in-place version. These ten cover strings, hashing, two pointers, trees, linked lists and dynamic programming.

Solve each yourself first. Python and Java solutions are given with complexity and the mistakes to avoid.

Problems10, easy to medium
LanguagesPython and Java
PatternsHashing, two pointers, trees, linked lists, DP
Follow-upsOften about space or in-place variants

What to expect from Apple coding problems

Apple's loops are team-specific, so the sourced facts do not fix a list of topics. Commonly reported practice is medium-difficulty problems on strings, arrays, linked lists, trees and hash maps, often with a follow-up about memory use or an in-place version. The ten problems here cover that mix and are practice problems, not real interview content.

Pair them with Apple interview questions for the fundamentals side.

Mistakes to watch for

Hiring status

Apple has announced no India engineering headcount. See Apple hiring for the sourced summary and apply only through Apple's own jobs site, jobs.apple.com, where Bengaluru and Hyderabad engineering roles are listed.

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

  1. 1

    Roman to Integer.

    easy

    Scan left to right: if a symbol is smaller than the one after it, subtract it, otherwise add it. This handles IV, IX, XL and so on without special cases. Time O(n), space O(1). Mistake: hard-coding all subtractive pairs as separate cases, or reading past the end on the last character.

    python
    def roman_to_int(s):
        v = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        total = 0
        for i, c in enumerate(s):
            if i + 1 < len(s) and v[c] < v[s[i+1]]: total -= v[c]
            else: total += v[c]
        return total
    java
    import java.util.*;
    class Solution {
        int romanToInt(String s) {
            Map<Character, Integer> v = Map.of('I',1,'V',5,'X',10,'L',50,'C',100,'D',500,'M',1000);
            int total = 0;
            for (int i = 0; i < s.length(); i++) {
                int cur = v.get(s.charAt(i));
                if (i + 1 < s.length() && cur < v.get(s.charAt(i + 1))) total -= cur; else total += cur;
            }
            return total;
        }
    }
  2. 2

    Group Anagrams.

    medium

    Words are anagrams if they have the same sorted letters or the same letter counts. Use that as a hash map key and collect words under it. With words of length k, sorting keys costs O(n k log k); count-tuple keys cost O(n k). Space O(n k). Mistake: using a list as a Python dictionary key (use a tuple or string).

    python
    from collections import defaultdict
    def group_anagrams(words):
        g = defaultdict(list)
        for w in words:
            g[''.join(sorted(w))].append(w)
        return list(g.values())
    java
    import java.util.*;
    class Solution {
        List<List<String>> groupAnagrams(String[] words) {
            Map<String, List<String>> g = new HashMap<>();
            for (String w : words) {
                char[] c = w.toCharArray(); Arrays.sort(c);
                g.computeIfAbsent(new String(c), k -> new ArrayList<>()).add(w);
            }
            return new ArrayList<>(g.values());
        }
    }
  3. 3

    3Sum: all unique triplets summing to zero.

    medium

    Sort, then fix the first number and use two pointers on the rest. Skip duplicate first numbers and, after finding a triplet, skip duplicates of both pointers. Time O(n squared), space O(1) beyond output. Mistake: using a set of tuples after a cubic search, or failing to skip duplicates so the output contains repeats.

    python
    def three_sum(a):
        a.sort(); res = []
        for i in range(len(a) - 2):
            if i and a[i] == a[i-1]: continue
            l, r = i + 1, len(a) - 1
            while l < r:
                s = a[i] + a[l] + a[r]
                if s < 0: l += 1
                elif s > 0: r -= 1
                else:
                    res.append([a[i], a[l], a[r]])
                    l += 1
                    while l < r and a[l] == a[l-1]: l += 1
        return res
    java
    import java.util.*;
    class Solution {
        List<List<Integer>> threeSum(int[] a) {
            Arrays.sort(a);
            List<List<Integer>> res = new ArrayList<>();
            for (int i = 0; i < a.length - 2; i++) {
                if (i > 0 && a[i] == a[i - 1]) continue;
                int l = i + 1, r = a.length - 1;
                while (l < r) {
                    int s = a[i] + a[l] + a[r];
                    if (s < 0) l++; else if (s > 0) r--;
                    else {
                        res.add(Arrays.asList(a[i], a[l], a[r])); l++;
                        while (l < r && a[l] == a[l - 1]) l++;
                    }
                }
            }
            return res;
        }
    }
  4. 4

    Find All Anagrams of p in s (start indices).

    medium

    Slide a window of length len(p) over s, keeping letter counts of the window and comparing with p's counts. Update by adding the entering character and removing the leaving one. Time O(n x 26) or O(n) with a match counter, space O(1). Mistake: rebuilding the counts for each window, which is O(n x |p|).

    python
    def find_anagrams(s, p):
        if len(p) > len(s): return []
        need, win, res = [0]*26, [0]*26, []
        for c in p: need[ord(c) - 97] += 1
        for i, c in enumerate(s):
            win[ord(c) - 97] += 1
            if i >= len(p): win[ord(s[i - len(p)]) - 97] -= 1
            if win == need: res.append(i - len(p) + 1)
        return res
    java
    import java.util.*;
    class Solution {
        List<Integer> findAnagrams(String s, String p) {
            List<Integer> res = new ArrayList<>();
            if (p.length() > s.length()) return res;
            int[] need = new int[26], win = new int[26];
            for (char c : p.toCharArray()) need[c - 'a']++;
            for (int i = 0; i < s.length(); i++) {
                win[s.charAt(i) - 'a']++;
                if (i >= p.length()) win[s.charAt(i - p.length()) - 'a']--;
                if (Arrays.equals(win, need)) res.add(i - p.length() + 1);
            }
            return res;
        }
    }
  5. 5

    Binary Tree Zigzag Level Order Traversal.

    medium

    Do a normal BFS by level, and reverse the order of every second level (or insert at the front of a deque). Time O(n), space O(n). Mistake: reversing the traversal order of the queue itself, which corrupts the next level; only reverse the collected values.

    python
    from collections import deque
    def zigzag(root):
        if not root: return []
        res, q, left = [], deque([root]), True
        while q:
            level = []
            for _ in range(len(q)):
                n = q.popleft(); level.append(n.val)
                if n.left: q.append(n.left)
                if n.right: q.append(n.right)
            res.append(level if left else level[::-1])
            left = not left
        return res
    java
    import java.util.*;
    class TreeNode { int val; TreeNode left, right; }
    class Solution {
        List<List<Integer>> zigzag(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if (root == null) return res;
            Deque<TreeNode> q = new ArrayDeque<>(); q.add(root);
            boolean left = true;
            while (!q.isEmpty()) {
                LinkedList<Integer> level = new LinkedList<>();
                for (int s = q.size(); s > 0; s--) {
                    TreeNode n = q.poll();
                    if (left) level.addLast(n.val); else level.addFirst(n.val);
                    if (n.left != null) q.add(n.left);
                    if (n.right != null) q.add(n.right);
                }
                res.add(level); left = !left;
            }
            return res;
        }
    }
  6. 6

    Inorder Successor in a BST.

    medium

    Walk from the root: if the node's value is greater than the target, it is a candidate successor and you go left; otherwise go right. The last candidate is the answer, or null. Time O(h), space O(1). Mistake: doing a full inorder traversal, which is O(n), and not handling the target being the largest node.

    python
    def successor(root, p):
        succ = None
        while root:
            if p.val < root.val:
                succ = root; root = root.left
            else:
                root = root.right
        return succ
    java
    class TreeNode { int val; TreeNode left, right; }
    class Solution {
        TreeNode successor(TreeNode root, TreeNode p) {
            TreeNode succ = null;
            while (root != null) {
                if (p.val < root.val) { succ = root; root = root.left; }
                else root = root.right;
            }
            return succ;
        }
    }
  7. 7

    Min Stack with O(1) getMin.

    medium

    Store each value with the minimum so far. Push computes the new minimum from the previous top, pop just removes, and getMin reads the top's second field. All operations O(1), space O(n). Mistake: tracking one global minimum variable, which becomes wrong after popping the minimum.

    python
    class MinStack:
        def __init__(self):
            self.s = []
        def push(self, x):
            self.s.append((x, min(x, self.s[-1][1]) if self.s else x))
        def pop(self):
            self.s.pop()
        def top(self):
            return self.s[-1][0]
        def get_min(self):
            return self.s[-1][1]
    java
    import java.util.*;
    class MinStack {
        private final Deque<int[]> s = new ArrayDeque<>();
        void push(int x) { s.push(new int[]{x, s.isEmpty() ? x : Math.min(x, s.peek()[1])}); }
        void pop() { s.pop(); }
        int top() { return s.peek()[0]; }
        int getMin() { return s.peek()[1]; }
    }
  8. 8

    Copy List with Random Pointer.

    medium

    Two passes with a hash map from old node to new node: first create all copies, then set next and random for each copy using the map. Time O(n), space O(n). An O(1)-space variant weaves copies between originals, sets random pointers, then unweaves. Mistake: copying the random pointer directly, which points into the original list.

    python
    def copy_random_list(head):
        m = {None: None}
        cur = head
        while cur:
            m[cur] = Node(cur.val); cur = cur.next
        cur = head
        while cur:
            m[cur].next = m[cur.next]
            m[cur].random = m[cur.random]
            cur = cur.next
        return m[head]
    java
    import java.util.*;
    class Node { int val; Node next, random; Node(int v) { val = v; } }
    class Solution {
        Node copyRandomList(Node head) {
            Map<Node, Node> m = new HashMap<>();
            for (Node c = head; c != null; c = c.next) m.put(c, new Node(c.val));
            for (Node c = head; c != null; c = c.next) {
                m.get(c).next = m.get(c.next);
                m.get(c).random = m.get(c.random);
            }
            return m.get(head);
        }
    }
  9. 9

    Word Break: can a string be segmented into dictionary words?

    medium

    DP over prefixes: dp[i] is true if some j < i has dp[j] true and s[j:i] is in the dictionary. Use a set for lookup and cap the inner loop at the longest word length. Time O(n x L) set lookups with substring cost, space O(n). Mistake: greedy longest-match, which fails on cases like 'catsandog'. See dynamic programming interview questions.

    python
    def word_break(s, words):
        ws, n = set(words), len(s)
        dp = [True] + [False] * n
        for i in range(1, n + 1):
            for j in range(i):
                if dp[j] and s[j:i] in ws:
                    dp[i] = True; break
        return dp[n]
    java
    import java.util.*;
    class Solution {
        boolean wordBreak(String s, List<String> words) {
            Set<String> ws = new HashSet<>(words);
            boolean[] dp = new boolean[s.length() + 1];
            dp[0] = true;
            for (int i = 1; i <= s.length(); i++)
                for (int j = 0; j < i; j++)
                    if (dp[j] && ws.contains(s.substring(j, i))) { dp[i] = true; break; }
            return dp[s.length()];
        }
    }
  10. 10

    Longest Substring Without Repeating Characters.

    medium

    Sliding window with a map from character to its last index. Move the left edge to one past the previous index of the current character when that index is inside the window, and track the best length. Time O(n), space O(min(n, alphabet)). Mistake: moving the left edge backwards when the stored index is older than the window start.

    python
    def longest_unique(s):
        last, l, best = {}, 0, 0
        for r, c in enumerate(s):
            if c in last and last[c] >= l: l = last[c] + 1
            last[c] = r
            best = max(best, r - l + 1)
        return best
    java
    import java.util.*;
    class Solution {
        int longestUnique(String s) {
            Map<Character, Integer> last = new HashMap<>();
            int l = 0, best = 0;
            for (int r = 0; r < s.length(); r++) {
                char c = s.charAt(r);
                if (last.containsKey(c) && last.get(c) >= l) l = last.get(c) + 1;
                last.put(c, r);
                best = Math.max(best, r - l + 1);
            }
            return best;
        }
    }

Frequently asked questions

Which language should I use for Apple coding questions?

Use whatever the role allows and you code best in. Read the posting: some teams expect Swift, Objective-C or C++.

Are Apple coding questions harder than Amazon's?

They are usually of similar difficulty. Apple follow-ups often probe memory and in-place solutions.

Is this a list of real Apple questions?

No. These are practice problems in a common style, not a record of real interviews.

Sources

Related guides

More in Company Interview Questions

See all in this section