Autocoder

Salesforce Coding Round Questions with Solutions in Python and Java

Last updated 2026-11-19

Salesforce asks for live coding in a language of your choice, with attention to edge cases and testing. These ten problems practise backtracking, recursion, grid search, stacks, hashing and union-find, which are common in this style of interview.

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

Problems10, medium to hard
LanguagesPython and Java
PatternsBacktracking, grids, hashing, union-find
Format describedShared-screen coding, then whiteboard-style in loops

What Salesforce coding problems tend to test

Salesforce describes coding in a language of your choice during the virtual screen and whiteboard-style coding in the loop, with attention to edge cases and testing. The problems that suit that format are backtracking and recursion exercises, grid and string handling and hashing or union-find problems that echo CRM data tasks such as merging records. These ten follow that style and are practice problems, not real interview content.

Pair them with Salesforce interview questions for the design and behavioural side.

Mistakes common in backtracking and grouping problems

Hiring status

For current Salesforce roles and dates, see Salesforce hiring and careers.salesforce.com. Salesforce cut nearly 1,000 jobs in early February 2026, per a Business Today report, so rely on its careers site for live openings.

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

  1. 1

    Word Search: does a word exist in a grid by moving to adjacent cells without reusing a cell?

    medium

    Backtracking DFS from every cell that matches the first letter. Mark the current cell as used (overwrite with a sentinel), explore four neighbours for the next letter, then restore the cell. Time O(R x C x 3^L) for word length L, space O(L). Mistake: forgetting to restore the cell after exploring, which blocks other paths.

    python
    def exist(board, word):
        R, C = len(board), len(board[0])
        def dfs(i, j, k):
            if k == len(word): return True
            if not (0 <= i < R and 0 <= j < C) or board[i][j] != word[k]: return False
            ch, board[i][j] = board[i][j], '#'
            ok = any(dfs(i+a, j+b, k+1) for a, b in ((1,0),(-1,0),(0,1),(0,-1)))
            board[i][j] = ch
            return ok
        return any(dfs(i, j, 0) for i in range(R) for j in range(C))
    java
    class Solution {
        boolean exist(char[][] b, String w) {
            for (int i = 0; i < b.length; i++)
                for (int j = 0; j < b[0].length; j++)
                    if (dfs(b, w, i, j, 0)) return true;
            return false;
        }
        private boolean dfs(char[][] b, String w, int i, int j, int k) {
            if (k == w.length()) return true;
            if (i < 0 || j < 0 || i >= b.length || j >= b[0].length || b[i][j] != w.charAt(k)) return false;
            char ch = b[i][j]; b[i][j] = '#';
            boolean ok = dfs(b, w, i+1, j, k+1) || dfs(b, w, i-1, j, k+1) || dfs(b, w, i, j+1, k+1) || dfs(b, w, i, j-1, k+1);
            b[i][j] = ch;
            return ok;
        }
    }
  2. 2

    Generate Parentheses: all valid combinations of n pairs.

    medium

    Backtrack building the string, adding '(' while fewer than n have been opened and ')' while closes are fewer than opens. Every generated string is valid by construction. The count is the Catalan number, so time is roughly O(4^n / sqrt(n)). Mistake: generating all 2^(2n) strings and filtering, which is far slower.

    python
    def generate(n):
        res = []
        def go(cur, o, c):
            if len(cur) == 2 * n: res.append(cur); return
            if o < n: go(cur + '(', o + 1, c)
            if c < o: go(cur + ')', o, c + 1)
        go('', 0, 0)
        return res
    java
    import java.util.*;
    class Solution {
        List<String> generate(int n) { List<String> r = new ArrayList<>(); go(r, "", 0, 0, n); return r; }
        private void go(List<String> r, String cur, int o, int c, int n) {
            if (cur.length() == 2 * n) { r.add(cur); return; }
            if (o < n) go(r, cur + "(", o + 1, c, n);
            if (c < o) go(r, cur + ")", o, c + 1, n);
        }
    }
  3. 3

    Subsets: all subsets of a list of distinct integers.

    medium

    Backtracking: at each index either include the element or skip it, recording the current path at every node. There are 2^n subsets, so time is O(n x 2^n) including copying, and space O(n) for recursion beyond the output. An iterative alternative doubles the result list by appending each new element to every existing subset. Mistake: appending the same list object instead of a copy.

    python
    def subsets(a):
        res = [[]]
        for x in a:
            res += [s + [x] for s in res]
        return res
    java
    import java.util.*;
    class Solution {
        List<List<Integer>> subsets(int[] a) {
            List<List<Integer>> res = new ArrayList<>();
            res.add(new ArrayList<>());
            for (int x : a) {
                int n = res.size();
                for (int i = 0; i < n; i++) {
                    List<Integer> s = new ArrayList<>(res.get(i)); s.add(x); res.add(s);
                }
            }
            return res;
        }
    }
  4. 4

    Valid Sudoku: check a partially filled 9 by 9 board.

    medium

    Track seen digits per row, per column and per 3 by 3 box using sets or bitmasks. The box index is (row // 3) x 3 + col // 3. Return false on the first duplicate. Time O(81), which is constant. Mistake: validating only rows and columns, or computing the box index wrongly. This checks validity, not solvability.

    python
    def is_valid_sudoku(b):
        rows = [set() for _ in range(9)]; cols = [set() for _ in range(9)]; boxes = [set() for _ in range(9)]
        for i in range(9):
            for j in range(9):
                v = b[i][j]
                if v == '.': continue
                k = i // 3 * 3 + j // 3
                if v in rows[i] or v in cols[j] or v in boxes[k]: return False
                rows[i].add(v); cols[j].add(v); boxes[k].add(v)
        return True
    java
    import java.util.*;
    class Solution {
        boolean isValidSudoku(char[][] b) {
            Set<String> seen = new HashSet<>();
            for (int i = 0; i < 9; i++)
                for (int j = 0; j < 9; j++) {
                    char v = b[i][j];
                    if (v == '.') continue;
                    if (!seen.add(v + "r" + i) || !seen.add(v + "c" + j) || !seen.add(v + "b" + (i / 3 * 3 + j / 3))) return false;
                }
            return true;
        }
    }
  5. 5

    Accounts Merge: merge accounts that share any email.

    hard

    Union-find over account indices: for each email, record the first account that owns it and union later accounts with it. Then group emails by root account, sort each group and prepend the name. Time O(N log N) for sorting N emails with near-constant union-find. Mistake: merging by name, since different people can share a name; the email is the identity.

    python
    def accounts_merge(accounts):
        parent = list(range(len(accounts)))
        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]; x = parent[x]
            return x
        owner = {}
        for i, acc in enumerate(accounts):
            for e in acc[1:]:
                if e in owner: parent[find(i)] = find(owner[e])
                else: owner[e] = i
        groups = {}
        for e, i in owner.items():
            groups.setdefault(find(i), []).append(e)
        return [[accounts[r][0]] + sorted(es) for r, es in groups.items()]
    java
    import java.util.*;
    class Solution {
        int[] p;
        int find(int x) { while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; } return x; }
        List<List<String>> accountsMerge(List<List<String>> accounts) {
            p = new int[accounts.size()];
            for (int i = 0; i < p.length; i++) p[i] = i;
            Map<String, Integer> owner = new HashMap<>();
            for (int i = 0; i < p.length; i++)
                for (String e : accounts.get(i).subList(1, accounts.get(i).size())) {
                    if (owner.containsKey(e)) p[find(i)] = find(owner.get(e)); else owner.put(e, i);
                }
            Map<Integer, TreeSet<String>> g = new HashMap<>();
            for (var en : owner.entrySet()) g.computeIfAbsent(find(en.getValue()), k -> new TreeSet<>()).add(en.getKey());
            List<List<String>> res = new ArrayList<>();
            for (var en : g.entrySet()) {
                List<String> row = new ArrayList<>(); row.add(accounts.get(en.getKey()).get(0)); row.addAll(en.getValue());
                res.add(row);
            }
            return res;
        }
    }
  6. 6

    Letter Combinations of a Phone Number.

    medium

    Backtrack digit by digit, trying each letter mapped to the current digit. Total results are the product of the letter counts, up to 4^n, so time is O(4^n x n). Return an empty list for empty input, not a list with an empty string. Mistake: handling the empty-input case wrongly.

    python
    def letter_combinations(digits):
        if not digits: return []
        m = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        res = ['']
        for d in digits:
            res = [p + c for p in res for c in m[d]]
        return res
    java
    import java.util.*;
    class Solution {
        List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            if (digits.isEmpty()) return res;
            String[] m = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            res.add("");
            for (char d : digits.toCharArray()) {
                List<String> next = new ArrayList<>();
                for (String p : res) for (char c : m[d - '0'].toCharArray()) next.add(p + c);
                res = next;
            }
            return res;
        }
    }
  7. 7

    Combination Sum: combinations of candidates (reusable) that sum to a target.

    medium

    Sort the candidates and backtrack: at each step try each candidate from the current index onward (so combinations are not repeated in different orders), subtracting from the target, and stop when a candidate exceeds the remaining target. Time is exponential, roughly O(N^(T/M)). Mistake: restarting the loop at index zero each call, which produces permutations of the same combination.

    python
    def combination_sum(c, target):
        c.sort(); res = []
        def go(i, rem, path):
            if rem == 0: res.append(path[:]); return
            for j in range(i, len(c)):
                if c[j] > rem: break
                path.append(c[j]); go(j, rem - c[j], path); path.pop()
        go(0, target, [])
        return res
    java
    import java.util.*;
    class Solution {
        List<List<Integer>> combinationSum(int[] c, int target) {
            Arrays.sort(c);
            List<List<Integer>> res = new ArrayList<>();
            go(c, 0, target, new ArrayList<>(), res);
            return res;
        }
        private void go(int[] c, int i, int rem, List<Integer> path, List<List<Integer>> res) {
            if (rem == 0) { res.add(new ArrayList<>(path)); return; }
            for (int j = i; j < c.length && c[j] <= rem; j++) {
                path.add(c[j]); go(c, j, rem - c[j], path, res); path.remove(path.size() - 1);
            }
        }
    }
  8. 8

    Evaluate Reverse Polish Notation.

    medium

    Use a stack: push numbers, and on an operator pop the right operand then the left, apply the operator and push the result. Division truncates toward zero, so in Python use int(a / b) and not floor division. Time O(n), space O(n). Mistake: reversing operand order, which matters for subtraction and division.

    python
    def eval_rpn(tokens):
        st = []
        for t in tokens:
            if t in '+-*/' and len(t) == 1:
                b, a = st.pop(), st.pop()
                st.append(a + b if t == '+' else a - b if t == '-' else a * b if t == '*' else int(a / b))
            else:
                st.append(int(t))
        return st[0]
    java
    import java.util.*;
    class Solution {
        int evalRPN(String[] tokens) {
            Deque<Integer> st = new ArrayDeque<>();
            for (String t : tokens) {
                switch (t) {
                    case "+": st.push(st.pop() + st.pop()); break;
                    case "*": st.push(st.pop() * st.pop()); break;
                    case "-": { int b = st.pop(), a = st.pop(); st.push(a - b); break; }
                    case "/": { int b = st.pop(), a = st.pop(); st.push(a / b); break; }
                    default: st.push(Integer.parseInt(t));
                }
            }
            return st.pop();
        }
    }
  9. 9

    Encode and Decode Strings: serialise a list of strings into one string and back.

    medium

    Prefix each string with its length and a delimiter, for example '5#hello'. To decode, read digits up to '#', convert to a length, take that many characters and continue. This is safe for any content, including '#' and digits, because the length tells you where the string ends. Time O(total length). Mistake: joining with a delimiter, which breaks when a string contains it.

    python
    def encode(strs):
        return ''.join(f'{len(s)}#{s}' for s in strs)
    
    def decode(s):
        res, i = [], 0
        while i < len(s):
            j = s.index('#', i)
            n = int(s[i:j])
            res.append(s[j+1:j+1+n])
            i = j + 1 + n
        return res
    java
    import java.util.*;
    class Codec {
        String encode(List<String> strs) {
            StringBuilder sb = new StringBuilder();
            for (String s : strs) sb.append(s.length()).append('#').append(s);
            return sb.toString();
        }
        List<String> decode(String s) {
            List<String> res = new ArrayList<>();
            int i = 0;
            while (i < s.length()) {
                int j = s.indexOf('#', i), n = Integer.parseInt(s.substring(i, j));
                res.add(s.substring(j + 1, j + 1 + n));
                i = j + 1 + n;
            }
            return res;
        }
    }
  10. 10

    Longest Consecutive Sequence in O(n).

    medium

    Put all numbers in a set. For each number that is the start of a run (its predecessor is not in the set), count upwards while the next number is present. Each number is visited at most twice, so time is O(n), space O(n). Mistake: sorting, which is O(n log n), or counting from every element, which degrades to O(n squared).

    python
    def longest_consecutive(a):
        s, best = set(a), 0
        for x in s:
            if x - 1 not in s:
                y = x
                while y + 1 in s: y += 1
                best = max(best, y - x + 1)
        return best
    java
    import java.util.*;
    class Solution {
        int longestConsecutive(int[] a) {
            Set<Integer> s = new HashSet<>();
            for (int x : a) s.add(x);
            int best = 0;
            for (int x : s)
                if (!s.contains(x - 1)) {
                    int y = x;
                    while (s.contains(y + 1)) y++;
                    best = Math.max(best, y - x + 1);
                }
            return best;
        }
    }

Frequently asked questions

Which language should I use for Salesforce coding?

Salesforce says you can code in a language of your choice in its virtual screen. Pick the one you are most fluent in.

Is whiteboard coding really used?

Salesforce's guidance describes whiteboard-style coding in its onsite loop. Practise writing code without an editor's help.

How should I test my solution in the interview?

Walk through a small example, then an empty input, a single element and a boundary case, out loud.

Sources

Related guides

More in Company Interview Questions

See all in this section