Autocoder

Meta Coding Round Questions with Solutions in Python and Java

Last updated 2026-11-19

Meta's coding screens are short, so speed with common patterns matters: two pointers, stacks, prefix sums with a hash map, BFS with an extra coordinate and heaps. These ten problems practise exactly those.

Time yourself at 15 to 20 minutes per problem, then compare with the worked solution in Python or Java.

Problems10, easy to medium
LanguagesPython and Java
PatternsTwo pointers, stacks, prefix sums, BFS, heaps
PaceAbout 15 to 20 minutes each

What Meta's coding questions emphasise

Meta's preparation material lists algorithms and data structures, recursion, binary trees, graphs with BFS and DFS, hash tables and heaps, and big-O analysis, and says initial screens are short, with older guidance mentioning about 35 minutes of coding. The practical consequence is that you should solve a medium problem cleanly in well under 20 minutes, which means practising string, array and tree problems until the patterns are automatic.

The ten problems below are practice in that style, not real interview content. For the rest of the loop see Meta interview questions.

Mistakes to avoid

Hiring status

For current Meta roles, see Meta hiring and metacareers.com. Meta cut nearly 8,000 jobs on 20 May 2026, according to the sourced report summarised on that page, so rely on its careers site for live openings.

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

  1. 1

    Valid Palindrome II: can the string become a palindrome after deleting at most one character?

    easy

    Two pointers from the ends. On the first mismatch, the answer is whether the string is a palindrome after skipping either the left or the right character. Time O(n), space O(1). Mistake: trying deletions at every position, which is O(n squared), or allowing a second skip.

    python
    def valid_palindrome(s):
        def ok(l, r):
            while l < r:
                if s[l] != s[r]: return False
                l += 1; r -= 1
            return True
        l, r = 0, len(s) - 1
        while l < r:
            if s[l] != s[r]: return ok(l + 1, r) or ok(l, r - 1)
            l += 1; r -= 1
        return True
    java
    class Solution {
        private boolean ok(String s, int l, int r) {
            while (l < r) if (s.charAt(l++) != s.charAt(r--)) return false;
            return true;
        }
        boolean validPalindrome(String s) {
            int l = 0, r = s.length() - 1;
            while (l < r) {
                if (s.charAt(l) != s.charAt(r)) return ok(s, l + 1, r) || ok(s, l, r - 1);
                l++; r--;
            }
            return true;
        }
    }
  2. 2

    Minimum Remove to Make Valid Parentheses.

    medium

    Scan left to right with a stack of indices of unmatched '('. A ')' with an empty stack is invalid and is marked for removal; at the end any indices left on the stack are unmatched '(' and are also removed. Rebuild the string without marked indices. Time O(n), space O(n). Mistake: counting only, which cannot tell which '(' to remove.

    python
    def min_remove(s):
        drop, st = set(), []
        for i, c in enumerate(s):
            if c == '(': st.append(i)
            elif c == ')':
                if st: st.pop()
                else: drop.add(i)
        drop |= set(st)
        return ''.join(c for i, c in enumerate(s) if i not in drop)
    java
    import java.util.*;
    class Solution {
        String minRemove(String s) {
            Set<Integer> drop = new HashSet<>();
            Deque<Integer> st = new ArrayDeque<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '(') st.push(i);
                else if (c == ')') { if (!st.isEmpty()) st.pop(); else drop.add(i); }
            }
            drop.addAll(st);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.length(); i++) if (!drop.contains(i)) sb.append(s.charAt(i));
            return sb.toString();
        }
    }
  3. 3

    Binary Tree Vertical Order Traversal.

    medium

    BFS with a column index: root is column 0, left child column minus one, right child column plus one. Group node values by column in a map and read columns from smallest to largest. BFS ensures nodes in the same column and row come out top to bottom, left to right. Time O(n), plus sorting keys O(n log n) or tracking min and max column to avoid it. Mistake: using DFS, which breaks top-to-bottom order inside a column.

    python
    from collections import deque, defaultdict
    def vertical(root):
        if not root: return []
        cols, q = defaultdict(list), deque([(root, 0)])
        while q:
            n, c = q.popleft()
            cols[c].append(n.val)
            if n.left: q.append((n.left, c - 1))
            if n.right: q.append((n.right, c + 1))
        return [cols[c] for c in sorted(cols)]
    java
    import java.util.*;
    class TreeNode { int val; TreeNode left, right; }
    class Solution {
        List<List<Integer>> vertical(TreeNode root) {
            TreeMap<Integer, List<Integer>> cols = new TreeMap<>();
            if (root == null) return new ArrayList<>();
            Deque<Object[]> q = new ArrayDeque<>();
            q.add(new Object[]{root, 0});
            while (!q.isEmpty()) {
                Object[] p = q.poll();
                TreeNode n = (TreeNode) p[0]; int c = (int) p[1];
                cols.computeIfAbsent(c, k -> new ArrayList<>()).add(n.val);
                if (n.left != null) q.add(new Object[]{n.left, c - 1});
                if (n.right != null) q.add(new Object[]{n.right, c + 1});
            }
            return new ArrayList<>(cols.values());
        }
    }
  4. 4

    Subarray Sum Equals K (array may contain negatives).

    medium

    Use prefix sums and a hash map of how many times each prefix sum has occurred. For each running sum s, the number of subarrays ending here with sum k equals count[s - k]. Seed the map with {0: 1} for subarrays starting at index zero. Time O(n), space O(n). Mistake: using a sliding window, which fails when negative numbers are present.

    python
    def subarray_sum(a, k):
        cnt, s, res = {0: 1}, 0, 0
        for x in a:
            s += x
            res += cnt.get(s - k, 0)
            cnt[s] = cnt.get(s, 0) + 1
        return res
    java
    import java.util.*;
    class Solution {
        int subarraySum(int[] a, int k) {
            Map<Integer, Integer> cnt = new HashMap<>();
            cnt.put(0, 1);
            int s = 0, res = 0;
            for (int x : a) {
                s += x;
                res += cnt.getOrDefault(s - k, 0);
                cnt.merge(s, 1, Integer::sum);
            }
            return res;
        }
    }
  5. 5

    K Closest Points to the Origin.

    medium

    Keep a max-heap of size k keyed by squared distance (skip the square root, since ordering is unchanged). Push each point and pop the farthest when the heap exceeds k. Time O(n log k), space O(k). Quickselect gives O(n) average. Mistake: sorting all points when k is small, or using floating-point square roots needlessly.

    python
    import heapq
    def k_closest(points, k):
        h = []
        for x, y in points:
            heapq.heappush(h, (-(x*x + y*y), x, y))
            if len(h) > k: heapq.heappop(h)
        return [[x, y] for _, x, y in h]
    java
    import java.util.*;
    class Solution {
        int[][] kClosest(int[][] pts, int k) {
            PriorityQueue<int[]> h = new PriorityQueue<>((a, b) -> Integer.compare(b[0]*b[0] + b[1]*b[1], a[0]*a[0] + a[1]*a[1]));
            for (int[] p : pts) { h.add(p); if (h.size() > k) h.poll(); }
            return h.toArray(new int[0][]);
        }
    }
  6. 6

    Dot Product of Two Sparse Vectors.

    medium

    Store only non-zero entries as index to value maps (or sorted index pairs). Iterate over the smaller map and look up in the other. Time O(min(a, b)) for a and b non-zero counts, and space is proportional to non-zero entries. Follow-up: if both are sorted lists, use two pointers or binary search. Mistake: storing the full dense arrays, which wastes memory and time.

    python
    class SparseVector:
        def __init__(self, nums):
            self.d = {i: v for i, v in enumerate(nums) if v}
        def dot(self, other):
            a, b = (self.d, other.d) if len(self.d) <= len(other.d) else (other.d, self.d)
            return sum(v * b[i] for i, v in a.items() if i in b)
    java
    import java.util.*;
    class SparseVector {
        private final Map<Integer, Integer> d = new HashMap<>();
        SparseVector(int[] nums) { for (int i = 0; i < nums.length; i++) if (nums[i] != 0) d.put(i, nums[i]); }
        int dot(SparseVector o) {
            Map<Integer, Integer> a = d.size() <= o.d.size() ? d : o.d, b = a == d ? o.d : d;
            int s = 0;
            for (var e : a.entrySet()) { Integer v = b.get(e.getKey()); if (v != null) s += e.getValue() * v; }
            return s;
        }
    }
  7. 7

    Simplify Path: canonical form of a Unix path.

    medium

    Split on '/' and process parts with a stack: ignore empty parts and '.', pop on '..' if the stack is not empty, otherwise push the name. Join with '/' and prefix a slash. Time O(n), space O(n). Mistakes: popping from an empty stack at the root, and treating '...' as a special name (it is an ordinary directory name).

    python
    def simplify(path):
        st = []
        for p in path.split('/'):
            if p == '..':
                if st: st.pop()
            elif p and p != '.':
                st.append(p)
        return '/' + '/'.join(st)
    java
    import java.util.*;
    class Solution {
        String simplify(String path) {
            Deque<String> st = new ArrayDeque<>();
            for (String p : path.split("/")) {
                if (p.equals("..")) { if (!st.isEmpty()) st.pollLast(); }
                else if (!p.isEmpty() && !p.equals(".")) st.addLast(p);
            }
            return "/" + String.join("/", st);
        }
    }
  8. 8

    Random Pick with Weight.

    medium

    Build prefix sums of the weights. To pick, draw a random integer in [1, total] and binary-search for the first prefix sum that is at least the draw. Construction O(n), each pick O(log n), space O(n). Mistake: drawing from [0, total) with the wrong comparison, which biases the first or last index.

    python
    import random, bisect
    class Solution:
        def __init__(self, w):
            self.pre = []
            s = 0
            for x in w:
                s += x
                self.pre.append(s)
        def pick_index(self):
            r = random.randint(1, self.pre[-1])
            return bisect.bisect_left(self.pre, r)
    java
    import java.util.*;
    class Solution {
        private final int[] pre;
        private final Random rnd = new Random();
        Solution(int[] w) {
            pre = new int[w.length];
            int s = 0;
            for (int i = 0; i < w.length; i++) { s += w[i]; pre[i] = s; }
        }
        int pickIndex() {
            int r = rnd.nextInt(pre[pre.length - 1]) + 1;
            int lo = 0, hi = pre.length - 1;
            while (lo < hi) { int m = (lo + hi) >>> 1; if (pre[m] >= r) hi = m; else lo = m + 1; }
            return lo;
        }
    }
  9. 9

    Buildings With an Ocean View (ocean is to the right).

    easy

    A building has a view if it is strictly taller than every building to its right. Scan right to left keeping the maximum height seen; record an index whenever its height exceeds that maximum, then reverse the result. Time O(n), space O(1) beyond output. Mistake: using greater-or-equal, which counts buildings of equal height that block the view.

    python
    def ocean_view(h):
        out, mx = [], 0
        for i in range(len(h) - 1, -1, -1):
            if h[i] > mx:
                out.append(i); mx = h[i]
        return out[::-1]
    java
    import java.util.*;
    class Solution {
        int[] oceanView(int[] h) {
            List<Integer> out = new ArrayList<>();
            int mx = 0;
            for (int i = h.length - 1; i >= 0; i--) if (h[i] > mx) { out.add(i); mx = h[i]; }
            Collections.reverse(out);
            return out.stream().mapToInt(Integer::intValue).toArray();
        }
    }
  10. 10

    Valid Word Abbreviation: does an abbreviation like 's10n' match a word?

    medium

    Walk two pointers. When the abbreviation has a digit, parse the whole number (reject a leading zero), skip that many characters in the word, otherwise compare letters. At the end both pointers must be exactly at the ends. Time O(n). Mistakes: allowing '0' or '01' as a skip, and not checking that the skip stays within the word length.

    python
    def valid_abbr(word, abbr):
        i = j = 0
        while i < len(word) and j < len(abbr):
            if abbr[j].isdigit():
                if abbr[j] == '0': return False
                n = 0
                while j < len(abbr) and abbr[j].isdigit():
                    n = n * 10 + int(abbr[j]); j += 1
                i += n
            else:
                if word[i] != abbr[j]: return False
                i += 1; j += 1
        return i == len(word) and j == len(abbr)
    java
    class Solution {
        boolean validAbbr(String word, String abbr) {
            int i = 0, j = 0;
            while (i < word.length() && j < abbr.length()) {
                char c = abbr.charAt(j);
                if (Character.isDigit(c)) {
                    if (c == '0') return false;
                    int n = 0;
                    while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) n = n * 10 + (abbr.charAt(j++) - '0');
                    i += n;
                } else {
                    if (word.charAt(i) != c) return false;
                    i++; j++;
                }
            }
            return i == word.length() && j == abbr.length();
        }
    }

Frequently asked questions

How many problems are in a Meta coding interview?

Older Meta guidance describes an initial screen of about 35 minutes of coding. Expect one or two problems per session and confirm with your recruiter.

Which language is best for Meta coding rounds?

Use the language you are fastest and most accurate in. Python and Java both work for all ten problems here.

Are these actual Meta interview problems?

No. They are practice problems in the style of the topics Meta lists, not a record of any real interview.

What should I read after this?

How to crack the Meta interview and the phone screen guide.

Sources

Related guides

More in Company Interview Questions

See all in this section