Salesforce Previous Year Coding Questions

Salesforce (makers of the world's leading CRM platform) is one of the most prestigious product companies for Indian engineers. With a major engineering centre in Hyderabad and offices in Bengaluru, Salesforce hires aggressively through campus placements at IITs, NITs, BITS, VIT, and Manipal. Freshers join as AMTS (Associate Member of Technical Staff) and experienced engineers join as MTS (Member of Technical Staff). The interview culture rewards clean, structured thinking — interviewers explicitly score your approach explanation and edge-case handling as much as correctness. The OA is on HackerRank (2–3 problems, 60 minutes) and filters on medium-difficulty problems solved cleanly. Technical rounds are pure DSA at AMTS level; MTS rounds layer in Low-Level Design (LLD) and High-Level Design (HLD). Salesforce's platform engineers often face questions related to data merging, graph connectivity, and interval scheduling — all directly relevant to CRM data management.


Hiring Process

Step 1: Resume Screening Salesforce shortlists based on CGPA (8+ preferred), internship quality, and relevant projects. CRM or enterprise software project experience is a differentiator but not mandatory for AMTS roles.

Step 2: Online Assessment (HackerRank) Duration: 60–90 minutes. Format: 2–3 DSA coding problems (Easy to Medium-Hard). Candidates who cleanly solve 2 out of 3 get shortlisted for ~30 interview slots per campus. Problems focus on arrays, strings, sorting, greedy, and DP. All test cases must pass — no partial scoring.

Step 3: Technical Interview 1 — DSA (45–60 mins) Pure DSA round. Starts with a warm-up easy/medium problem, then escalates. Interviewers probe time/space complexity for every approach and ask you to optimise your initial solution.

Step 4: Technical Interview 2 — DSA + LLD (60 mins) One medium-to-hard DSA problem followed by an LLD question (Parking Lot, LRU Cache, or Snake and Ladder game). Clean OOP code with proper encapsulation is expected.

Step 5: Hiring Manager / Behavioural Round (30–45 mins) Discussion of past projects, career goals, and Salesforce's four core values: Trust, Customer Success, Innovation, and Equality. MTS candidates also get an HLD discussion (design a CRM notification system, search pipeline, or data sync engine).

Tips: Arrays and strings are the highest-frequency topic — master every sliding window, two-pointer, and hashing pattern. For LLD, prepare Parking Lot, LRU Cache, and Tic-Tac-Toe thoroughly. For HLD (MTS), think in terms of data consistency and sync — Salesforce's core challenge is syncing CRM data reliably across millions of customers. Communicate your thought process before writing any code; Salesforce interviewers explicitly score structured thinking.


Preparation Resources

Part 1 — OA Questions

1. Maximum Product Subarray Medium

OADynamic Programming · ArraysLeetCode: #152

Find the contiguous subarray with the largest product. Reported in Salesforce HackerRank OA — tests handling of negative numbers that flip the sign of the product.

Input: nums = [2,3,-2,4]
Output: 6  (subarray [2,3])

Input: nums = [-2,3,-4]
Output: 24

Approach: Track both currentMax and currentMin at each step — a negative times a negative becomes a positive. newMax = max(num, currentMaxnum, currentMinnum); newMin = min(same). Update global max from newMax. **Complexity: Time O(n) · Space O(1) Follow-up: Maximum Subarray (LC #53) using Kadane's — simpler variant without sign-flip concern.


2. Kth Largest Element in an Array Medium

OAHeap · Quickselect · SortingLeetCode: #215

Find the kth largest element in an unsorted array without fully sorting it. Salesforce OA variant: for each window of size k, return the kth greatest element.

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Approach: Min-heap of size k. Iterate all elements; if heap exceeds k, pop the minimum. The heap top is the kth largest. Alternatively, Quickselect gives O(n) average time. Complexity: Heap: Time O(n log k) · Space O(k) | Quickselect: Time O(n) avg · Space O(1) Follow-up: Top K Frequent Elements (LC #347) — find k most frequent values using the same heap pattern.


3. Snakes and Ladders Medium

OABFS · Graph · SimulationLeetCode: #909

Find the minimum dice throws to reach the last cell of a Snakes and Ladders board (Boustrophedon numbering). Reported directly in Salesforce OA as a minimum-steps-on-board problem.

Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],
               [-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],
               [-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]
Output: 4

Approach: BFS from cell 1. For each cell, simulate all 6 dice outcomes. Convert cell number to (row, col) handling Boustrophedon row alternation. If board[r][c] != -1, jump to that destination. Return minimum steps when nn is reached. *Complexity: Time O(n²) · Space O(n²) Follow-up: Design a multiplayer Snakes and Ladders game class (LLD) — a common follow-up in Salesforce onsite rounds.


4. Rearrange Array Elements by Sign Medium

OAArrays · Two PointersLeetCode: #2149

Rearrange an array with equal counts of positive and negative integers so they alternate starting with a positive, preserving relative order within each group. Reported in Salesforce OA.

Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]

Input: nums = [-1,1]
Output: [1,-1]

Approach: Two index pointers — posIdx = 0 (even positions), negIdx = 1 (odd positions). Allocate a result array. Positive numbers fill even positions (posIdx += 2), negatives fill odd positions (negIdx += 2). Complexity: Time O(n) · Space O(n) Follow-up: Wiggle Sort II (LC &#35;324) — rearrange so nums[0] < nums[1] > nums[2] < nums[3]...


5. Find the Duplicate Number Medium

OAArrays · Floyd's Cycle DetectionLeetCode: #287

Given an array of n+1 integers where each value is in [1, n], find the one duplicate using O(1) extra space without modifying the array.

Input: nums = [1,3,4,2,2]
Output: 2

Input: nums = [3,1,3,4,2]
Output: 3

Approach: Floyd's cycle detection. Treat the array as a linked list where index i points to nums[i]. The duplicate creates a cycle. Phase 1: find intersection with slow (1 step) and fast (2 steps) pointers. Phase 2: reset one pointer to index 0, advance both 1 step — they meet at the duplicate. Complexity: Time O(n) · Space O(1) Follow-up: Find All Duplicates in an Array (LC &#35;442) — each element appears once or twice; use sign negation to find all duplicates.


6. Minimum Number of Arrows to Burst Balloons Medium

OAGreedy · Intervals · SortingLeetCode: #452

Find the minimum number of vertical arrows to burst all balloons (horizontal intervals on x-axis). An arrow at x bursts [xstart, xend] if xstart ≤ x ≤ xend.

Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2

Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4

Approach: Sort by end coordinate. Shoot an arrow at the end of the first balloon — it bursts all currently overlapping balloons. When the next balloon's start exceeds the current arrow position, fire a new arrow. Complexity: Time O(n log n) · Space O(1) Follow-up: Non-overlapping Intervals (LC &#35;435) — same greedy logic: count minimum intervals to remove so the rest don't overlap.


Part 2 — Phone Screen Questions

7. Two Sum Easy

Phone ScreenArrays · HashingLeetCode: #1

Given an array and a target, return indices of the two numbers that sum to the target. Classic Salesforce warm-up — interviewers follow up asking for the O(n) solution.

Input: nums = [2,7,11,15], target = 9
Output: [0,1]

Input: nums = [3,2,4], target = 6
Output: [1,2]

Approach: Hash map (value → index). For each element, check if (target - element) exists in the map. If yes, return both indices. Complexity: Time O(n) · Space O(n) Follow-up: Two Sum II — sorted array (LC &#35;167) using two pointers for O(1) space.


8. Valid Anagram Easy

Phone ScreenStrings · HashingLeetCode: #242

Determine if two strings are anagrams (same characters, same frequencies).

Input: s = "anagram", t = "nagaram"
Output: true

Input: s = "rat", t = "car"
Output: false

Approach: 26-element frequency array. Increment for each char of s, decrement for each char of t. If all counts are zero, they are anagrams. Complexity: Time O(n) · Space O(1) Follow-up: Group Anagrams (LC &#35;49) — group all anagram strings from an array using sorted string as key.


9. Longest Common Prefix Easy

Phone ScreenStrings · TrieLeetCode: #14

Find the longest common prefix string among an array of strings. Return "" if none exists.

Input: strs = ["flower","flow","flight"]
Output: "fl"

Input: strs = ["dog","racecar","car"]
Output: ""

Approach: Use the first string as the reference prefix. Compare with each subsequent string; shorten the prefix on any mismatch. Stop early if prefix becomes empty. Complexity: Time O(S) where S = total characters · Space O(1) Follow-up: Implement this using a Trie — insert all strings and traverse the longest single-child path from the root.


10. Reverse Words in a String Medium

Phone ScreenStrings · Two PointersLeetCode: #151

Reverse the order of words in a string. Strip leading/trailing spaces and reduce multiple spaces to one.

Input: s = "the sky is blue"
Output: "blue is sky the"

Input: s = "  hello world  "
Output: "world hello"

Approach: Split on whitespace filtering empty strings, reverse the word array, join with a single space. In-place: reverse the entire string, then reverse each word individually. Complexity: Time O(n) · Space O(n) Follow-up: Reverse Words in a String III (LC &#35;557) — reverse letters within each word but keep word order.


11. Group Anagrams Medium

Phone ScreenHashing · Strings · SortingLeetCode: #49

Group an array of strings so all anagrams appear together. Reported in multiple Salesforce phone screens.

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Approach: Hash map keyed by the sorted version of each string. Each string is appended to its group. Return the map values. Complexity: Time O(n * k log k) where k = max string length · Space O(nk) Follow-up: Use a 26-integer frequency array as the key for O(nk) time without sorting.


12. LRU Cache Medium

Phone ScreenDesign · Doubly Linked List · HashingLeetCode: #146

Design an LRU Cache with O(1) get and O(1) put. The most commonly reported LLD question in Salesforce phone screens and onsite rounds.

LRUCache cache = new LRUCache(2);
cache.put(1,1); cache.put(2,2);
cache.get(1);    // 1
cache.put(3,3);  // evicts key 2
cache.get(2);    // -1
cache.put(4,4);  // evicts key 1
cache.get(1);    // -1
cache.get(3);    // 3
cache.get(4);    // 4

Approach: Doubly linked list (O(1) remove/insert) + hash map (key → node). On get: move node to front. On put: insert at front; if over capacity, remove the tail node and evict its key from the map. Sentinel head/tail nodes simplify boundary handling. Complexity: Time O(1) per operation · Space O(capacity) Follow-up: LFU Cache (LC &#35;460) — evict the Least Frequently Used key instead; ties broken by recency.


13. Implement Trie (Prefix Tree) Medium

Phone ScreenTrie · Design · StringsLeetCode: #208

Implement a Trie with insert, search, and startsWith. Reported in Salesforce phone screens — directly relevant to CRM search and autocomplete features.

Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // true
trie.search("app");     // false
trie.startsWith("app"); // true
trie.insert("app");
trie.search("app");     // true

Approach: Each TrieNode has 26 children and an isEnd boolean. insert: traverse/create nodes per character, mark last as end. search: traverse; return isEnd. startsWith: traverse; return true if all nodes exist. Complexity: Time O(L) per op · Space O(total chars) Follow-up: Design Add and Search Words (LC &#35;211) — support '.' wildcard matching with DFS.


Part 3 — Onsite Questions

14. Number of Islands Medium

OnsiteBFS/DFS · Grid · GraphLeetCode: #200

Count connected groups of 1s (islands) in a binary grid. Reported in multiple Salesforce onsite rounds.

Input: grid = [["1","1","0"],["1","1","0"],["0","0","1"]]
Output: 2

Approach: DFS from each unvisited '1'. Mark all reachable cells as visited (set to '0'). Increment island count each time a new DFS starts. Complexity: Time O(m*n) · Space O(m*n) Follow-up: Accounts Merge (LC &#35;721) — same Union-Find/DFS connectivity concept applied to CRM contact data.


15. Merge Intervals Medium

OnsiteArrays · Sorting · IntervalsLeetCode: #56

Merge all overlapping intervals and return the non-overlapping result. Salesforce frames this as merging overlapping data sync windows in a CRM pipeline.

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]

Approach: Sort by start time. If current.start ≤ last merged.end, extend last.end = max(last.end, current.end). Otherwise push current as new interval. Complexity: Time O(n log n) · Space O(n) Follow-up: Insert Interval (LC &#35;57) — insert a new interval into a sorted non-overlapping list and re-merge.


16. Longest Substring Without Repeating Characters Medium

OnsiteSliding Window · Strings · HashingLeetCode: #3

Find the length of the longest substring without any repeating characters.

Input: s = "abcabcbb"
Output: 3  ("abc")

Input: s = "pwwkew"
Output: 3  ("wke")

Approach: Sliding window with a hash map (char → last seen index). Maintain left pointer; when a repeat is found, advance left to max(left, lastSeen[char]+1). Update max window at each step. Complexity: Time O(n) · Space O(min(n, charset)) Follow-up: Minimum Window Substring (LC &#35;76) — smallest window containing all characters of a target string.


17. Product of Array Except Self Medium

OnsiteArrays · Prefix ProductLeetCode: #238

Return an array where output[i] is the product of all elements except nums[i]. Division is NOT allowed.

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Approach: Two passes. Left pass: output[i] = product of all elements to the left. Right pass: multiply output[i] by a running right product (product of all elements to the right). O(1) extra space beyond the output array. Complexity: Time O(n) · Space O(1) Follow-up: Handle zeros in the array explicitly — one-zero case vs two-or-more-zeros case.


18. Find All Anagrams in a String Medium

OnsiteSliding Window · Strings · HashingLeetCode: #438

Find all starting indices of anagrams of pattern p in string s.

Input: s = "cbaebabacd", p = "abc"
Output: [0,6]

Input: s = "abab", p = "ab"
Output: [0,1,2]

Approach: Fixed sliding window of size p.length. Maintain frequency counts for window and pattern plus a 'matches' counter. Slide window: update matches on entry and exit of each character. Complexity: Time O(n) · Space O(1) Follow-up: Permutation in String (LC &#35;567) — return true if any permutation of p is a substring of s.


19. Minimum Window Substring Hard

OnsiteSliding Window · Strings · HashingLeetCode: #76

Find the minimum window substring of s that contains all characters of t (including duplicates).

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"

Approach: Two pointers. Expand right to include all required characters. Once all satisfied, contract left to minimise the window. Track required characters with a frequency map and a 'formed' counter. Complexity: Time O(|s|+|t|) · Space O(|s|+|t|) Follow-up: Minimum Window with all distinct chars of t — simpler variant when t has no repeats.


20. Spiral Matrix Medium

OnsiteArrays · Simulation · MatrixLeetCode: #54

Return all elements of a matrix in spiral order (right → down → left → up, layer by layer).

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Approach: Shrinking boundaries (top, bottom, left, right). Traverse each boundary in order → ↓ ← ↑, then shrink. Check boundary validity before each direction to avoid double-traversal on single rows/columns. Complexity: Time O(m*n) · Space O(1) Follow-up: Spiral Matrix II (LC &#35;59) — generate an n×n matrix filled 1 to n² in spiral order.


21. Search in Rotated Sorted Array Medium

OnsiteBinary Search · ArraysLeetCode: #33

Search for a target in a rotated sorted array in O(log n) time.

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

Approach: Modified binary search. At each mid, determine which half is sorted: if nums[left] ≤ nums[mid], left half is sorted. Check if target falls in the sorted half; search there; otherwise search the other half. Complexity: Time O(log n) · Space O(1) Follow-up: Search in Rotated Sorted Array II (LC &#35;81) — with duplicates; worst case degrades to O(n).


22. Binary Tree Level Order Traversal Medium

OnsiteTrees · BFS · QueueLeetCode: #102

Return the level-order traversal of a binary tree's node values as a list of lists (one list per level).

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Approach: BFS with a queue. At the start of each level, record the current queue size. Process exactly that many nodes, enqueue their children, collect their values into a level list. Complexity: Time O(n) · Space O(n) Follow-up: Binary Tree Zigzag Level Order Traversal (LC &#35;103) — alternate direction each level.


23. Binary Tree Right Side View Medium

OnsiteTrees · BFS · DFSLeetCode: #199

Return the values of nodes visible when looking at the tree from the right side (the rightmost node at each level).

Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Approach: BFS level-order; the last node processed at each level is the rightmost visible node. Alternatively, right-first DFS: record the first node at each depth. Complexity: Time O(n) · Space O(n) Follow-up: Return the left side view — take the first node at each level instead of the last.


24. Lowest Common Ancestor of a Binary Tree Medium

OnsiteTrees · DFS · RecursionLeetCode: #236

Given a binary tree and two nodes p and q, find their Lowest Common Ancestor.

Input: root = [3,5,1,6,2,0,8], p = 5, q = 1
Output: 3

Input: root = [3,5,1,6,2,0,8], p = 5, q = 4
Output: 5

Approach: Post-order recursive DFS. If root is null/p/q, return root. Recurse left and right. If both return non-null, current node is the LCA. Otherwise propagate the non-null side upward. Complexity: Time O(n) · Space O(h) Follow-up: LCA in a BST (LC &#35;235) — use BST property to navigate without full traversal.


25. Word Search Medium

OnsiteBacktracking · DFS · GridLeetCode: #79

Determine if a word exists in a 2D character grid via sequentially adjacent cells (each cell used at most once).

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Approach: DFS backtracking from every cell. Mark cells visited by temporarily changing the character. Recursively check all 4 directions for the next character. Unmark on backtrack. Complexity: Time O(m*n*4^L) · Space O(L) Follow-up: Word Search II (LC &#35;212) — find all words from a dictionary on the board using a Trie + DFS.


26. Course Schedule Medium

OnsiteGraph · Topological Sort · Cycle DetectionLeetCode: #207

Given course prerequisites as directed edges, determine if all courses can be completed (no cycle in the dependency graph).

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false

Approach: DFS cycle detection with 3 states (unvisited, in-progress, done). A cycle is detected when an in-progress node is revisited. Alternatively, Kahn's BFS using in-degree counts. Complexity: Time O(V+E) · Space O(V+E) Follow-up: Course Schedule II (LC &#35;210) — return the actual topological ordering.


27. Accounts Merge Medium

OnsiteUnion-Find · DFS · HashingLeetCode: #721

Merge accounts where any two accounts sharing an email belong to the same person. Return merged accounts with sorted emails. Directly relevant to Salesforce CRM's contact deduplication feature.

Input: accounts = [["John","a@mail.com","b@mail.com"],["John","a@mail.com","c@mail.com"],["Mary","d@mail.com"]]
Output: [["John","a@mail.com","b@mail.com","c@mail.com"],["Mary","d@mail.com"]]

Approach: Union-Find — map each email to an account index; union accounts sharing an email. Group emails by their root representative. Sort each group and prepend the account name. Complexity: Time O(N log N) where N = total emails · Space O(N) Follow-up: How would you design a real-time contact deduplication system at Salesforce scale (1B+ contacts)?


28. Decode Ways Medium

OnsiteDynamic Programming · StringsLeetCode: #91

Count the number of ways to decode a string of digits where 'A'→1, ..., 'Z'→26.

Input: s = "12"
Output: 2  ("AB" or "L")

Input: s = "226"
Output: 3  ("BZ", "VF", "BBF")

Input: s = "06"
Output: 0

Approach: DP where dp[i] = ways to decode s[0..i). dp[i] += dp[i-1] if s[i-1] is valid (not '0'). dp[i] += dp[i-2] if s[i-2..i) forms a valid two-digit code (10–26). Use two variables for O(1) space. Complexity: Time O(n) · Space O(1) Follow-up: Decode Ways II (LC &#35;639) — '*' can represent any digit 1–9.


29. Coin Change Medium

OnsiteDynamic Programming · BFSLeetCode: #322

Find the minimum number of coins to make a given amount. Return -1 if impossible.

Input: coins = [1,5,11], amount = 15
Output: 3  (5+5+5)

Input: coins = [2], amount = 3
Output: -1

Approach: Bottom-up DP. dp[i] = minimum coins for amount i. Initialise all to infinity except dp[0] = 0. For each amount 1 to target, try each coin: dp[i] = min(dp[i], dp[i-coin]+1). Complexity: Time O(amount * n) · Space O(amount) Follow-up: Coin Change II (LC &#35;518) — count the number of distinct combinations (not minimum count).


30. House Robber Medium

OnsiteDynamic Programming · ArraysLeetCode: #198

Maximise the amount you can rob from houses in a line without robbing two adjacent houses.

Input: nums = [1,2,3,1]
Output: 4

Input: nums = [2,7,9,3,1]
Output: 12

Approach: Two rolling variables. At each house: newVal = max(prev1, prev2 + nums[i]); update prev2 = prev1, prev1 = newVal. Complexity: Time O(n) · Space O(1) Follow-up: House Robber II (LC &#35;213) — houses in a circle; run linear DP twice (exclude first or last house).


31. Unique Paths Medium

OnsiteDynamic Programming · Math · GridLeetCode: #62

Count distinct paths from top-left to bottom-right of an m×n grid, moving only right or down.

Input: m = 3, n = 7
Output: 28

Approach: dp[i][j] = dp[i-1][j] + dp[i][j-1]. First row and column are all 1s. Can reduce to a single-row rolling array for O(n) space. Complexity: Time O(m*n) · Space O(n) Follow-up: Unique Paths II (LC &#35;63) — grid has obstacles; cells with obstacles have dp value 0.


32. Serialize and Deserialize Binary Tree Hard

OnsiteTrees · BFS · DesignLeetCode: #297

Design an algorithm to serialize a binary tree to a string and deserialize it back to the original tree structure.

Input: root = [1,2,3,null,null,4,5]
Serialize: "1,2,3,null,null,4,5"
Deserialize: same tree

Approach: BFS level-order serialization. Write each node value or "null" separated by commas. Deserialize by reading tokens with a queue: create root from first token, then for each node dequeued read the next two tokens as left and right children. Complexity: Time O(n) · Space O(n) Follow-up: Serialize and Deserialize N-ary Tree (LC &#35;428) — extend to handle N children per node.


33. Path Sum II Medium

OnsiteTrees · DFS · BacktrackingLeetCode: #113

Find all root-to-leaf paths where the sum of node values equals targetSum.

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]

Approach: DFS backtracking. Maintain current path and running sum. At each leaf, if sum equals target, add a copy of the path. Backtrack by removing the last node after returning. Complexity: Time O(n) · Space O(h) Follow-up: Path Sum III (LC &#35;437) — count paths summing to target (not root-to-leaf); use prefix sum hash map.


34. Maximum Depth of Binary Tree Easy

OnsiteTrees · DFSLeetCode: #104

Find the maximum depth (longest root-to-leaf path length) of a binary tree.

Input: root = [3,9,20,null,null,15,7]
Output: 3

Approach: Recursive DFS. maxDepth(node) = 1 + max(maxDepth(node.left), maxDepth(node.right)). Base case: null returns 0. Complexity: Time O(n) · Space O(h) Follow-up: Minimum Depth (LC &#35;111) — minimum depth is the distance to the nearest LEAF, not null child.


35. Symmetric Tree Easy

OnsiteTrees · DFS · BFSLeetCode: #101

Check if a binary tree is a mirror of itself (symmetric around its centre). Interviewers ask for both recursive and iterative solutions.

Input: root = [1,2,2,3,4,4,3]
Output: true

Input: root = [1,2,2,null,3,null,3]
Output: false

Approach: Recursive isMirror(left, right) — values must be equal, left.left mirrors right.right, and left.right mirrors right.left. Iterative: BFS with two queues, one per side. Complexity: Time O(n) · Space O(h) Follow-up: Subtree of Another Tree (LC &#35;572) — uses the same-tree comparison recursively.


36. Min Stack Medium

OnsiteDesign · StacksLeetCode: #155

Design a stack supporting push, pop, top, and getMin — all in O(1) time.

MinStack stack = new MinStack();
stack.push(-2); stack.push(0); stack.push(-3);
stack.getMin(); // -3
stack.pop();
stack.top();    // 0
stack.getMin(); // -2

Approach: Two stacks — main and auxiliary min stack. On push: push to main, push min(val, minStack.top()) to min stack. On pop: pop both. getMin() returns minStack.top(). Complexity: Time O(1) per operation · Space O(n) Follow-up: Max Stack (LC &#35;716) — also support popMax() removing the maximum element.


37. Daily Temperatures Medium

OnsiteMonotonic Stack · ArraysLeetCode: #739

Given daily temperatures, return an array where answer[i] is the number of days until a warmer temperature; 0 if none.

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]

Approach: Monotonic decreasing stack of indices. For each temperature, pop all indices with smaller temperatures (their wait = current index - popped index). Push current index. Complexity: Time O(n) · Space O(n) Follow-up: Next Greater Element II (LC &#35;503) — circular array; process the array twice to simulate wrapping.


38. Top K Frequent Elements Medium

OnsiteHeap · Bucket Sort · HashingLeetCode: #347

Return the k most frequent elements. Salesforce frames this as returning the k most-used CRM features from usage logs.

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Approach: Frequency map + min-heap of size k. After processing all elements, the heap contains the k most frequent. Bucket Sort alternative: frequency buckets indexed 0 to n; collect from the last non-empty bucket. Complexity: Heap: Time O(n log k) · Bucket: Time O(n) Follow-up: Sort Characters By Frequency (LC &#35;451) — sort all characters by frequency.


39. Linked List Cycle Easy

OnsiteLinked Lists · Floyd's CycleLeetCode: #141

Detect if a linked list has a cycle using O(1) memory.

Input: head = [3,2,0,-4] (tail connects to node at index 1)
Output: true

Approach: Floyd's two-pointer (tortoise and hare). Slow moves 1 step, fast moves 2. If they meet, there is a cycle. If fast reaches null, no cycle. Complexity: Time O(n) · Space O(1) Follow-up: Linked List Cycle II (LC &#35;142) — find the exact node where the cycle begins.


40. Remove Nth Node From End of List Medium

OnsiteLinked Lists · Two PointersLeetCode: #19

Remove the nth node from the end of a linked list in one pass.

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Approach: Dummy head + two pointers. Advance fast pointer n+1 steps. Then advance both until fast reaches null. slow is now before the node to remove. Set slow.next = slow.next.next. Complexity: Time O(L) · Space O(1) Follow-up: Find middle of linked list (LC &#35;876) — same two-pointer pattern with fast moving 2x.


41. Reorder List Medium

OnsiteLinked Lists · Two PointersLeetCode: #143

Reorder a linked list from L0→L1→...→Ln to L0→Ln→L1→Ln-1→L2→Ln-2→... in-place.

Input: head = [1,2,3,4]
Output: [1,4,2,3]

Approach: Three steps: (1) Find midpoint using slow/fast pointers. (2) Reverse the second half. (3) Merge the two halves by interleaving nodes. Complexity: Time O(n) · Space O(1) Follow-up: Can you do this recursively? Yes, but the call stack uses O(n) space.


42. Climbing Stairs Easy

OnsiteDynamic Programming · FibonacciLeetCode: #70

Count distinct ways to climb n stairs taking 1 or 2 steps at a time. Reported as a warm-up problem in Salesforce onsite rounds.

Input: n = 3
Output: 3

Approach: ways(n) = ways(n-1) + ways(n-2). Use two rolling variables (no array needed). Complexity: Time O(n) · Space O(1) Follow-up: Min Cost Climbing Stairs (LC &#35;746) — minimise total cost to reach the top.


43. Find Median from Data Stream Hard

OnsiteHeap · Design · Data StreamsLeetCode: #295

Design a data structure to add numbers from a stream and find the median at any time. Reported in Salesforce MTS onsite — relevant to real-time CRM analytics.

MedianFinder mf = new MedianFinder();
mf.addNum(1); mf.addNum(2);
mf.findMedian(); // 1.5
mf.addNum(3);
mf.findMedian(); // 2.0

Approach: Two heaps — max-heap for lower half and min-heap for upper half. Maintain invariant: sizes differ by at most 1. Median = max-heap top (odd total) or average of both tops (even). Complexity: Time O(log n) per addNum · O(1) per findMedian · Space O(n) Follow-up: Sliding Window Median (LC &#35;480) — median within a sliding window using lazy deletion.


44. Rotate Image Medium

OnsiteArrays · Matrix · MathLeetCode: #48

Rotate an n×n matrix 90 degrees clockwise in-place.

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Approach: Two-step in-place: (1) Transpose (swap matrix[i][j] with matrix[j][i]). (2) Reverse each row. This achieves 90° clockwise rotation without extra space. Complexity: Time O(n²) · Space O(1) Follow-up: Counter-clockwise rotation: reverse each column (or transpose then reverse columns).


45. 3Sum Medium

OnsiteTwo Pointers · Sorting · ArraysLeetCode: #15

Find all unique triplets in an array that sum to zero.

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Approach: Sort. Fix first element with index i. Two-pointer the rest for pairs summing to -nums[i]. Skip duplicates of i and after each match. Complexity: Time O(n²) · Space O(1) Follow-up: 4Sum (LC &#35;18) — add another outer loop; same two-pointer pattern for the inner pair.


46. Design Add and Search Words Data Structure Medium

OnsiteTrie · DFS · DesignLeetCode: #211

Design a data structure supporting addWord and search where '.' matches any single character. Relevant to Salesforce SOQL wildcard search.

WordDictionary wd = new WordDictionary();
wd.addWord("bad"); wd.addWord("dad"); wd.addWord("mad");
wd.search(".ad"); // true
wd.search("b.."); // true
wd.search("pad"); // false

Approach: Trie for addWord. For search, DFS: at non-dot chars traverse normally; at '.' recursively try all 26 children. Complexity: addWord O(L) · search O(26^L) worst case · Space O(total chars) Follow-up: Word Search II (LC &#35;212) — find all matching words on a 2D board using Trie + DFS.


47. Trapping Rain Water Hard

OnsiteTwo Pointers · Stack · DPLeetCode: #42

Compute how much rainwater can be trapped between bars given their heights.

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Input: height = [4,2,0,3,2,5]
Output: 9

Approach: Two pointers. Track leftMax and rightMax. Whichever side has the smaller max determines trapped water at that position: water += min(leftMax, rightMax) - height[ptr]. Advance the smaller-max side. Complexity: Time O(n) · Space O(1) Follow-up: Trapping Rain Water II (LC &#35;407) — 2D elevation map; use a min-heap border expansion.


48. Clone Graph Medium

OnsiteGraph · BFS · HashingLeetCode: #133

Return a deep copy of an undirected graph where each node has a value and a list of neighbours.

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: deep copy (distinct node objects, same structure)

Approach: BFS with a hash map (original → clone). For each node dequeued, iterate its neighbours; create clones for new ones and enqueue them. Add cloned neighbours to the current clone's list. Complexity: Time O(V+E) · Space O(V) Follow-up: Salesforce variant — clone a directed relationship graph of Salesforce Org objects (Users → Accounts → Opportunities).


49. Rotate Array Medium

OnsiteArrays · Two Pointers · MathLeetCode: #189

Rotate an array to the right by k steps in-place using O(1) extra space.

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]

Approach: Three-reverse trick. k = k % n. (1) Reverse entire array. (2) Reverse nums[0..k-1]. (3) Reverse nums[k..n-1]. Achieves rotation in O(1) space. Complexity: Time O(n) · Space O(1) Follow-up: Rotate Matrix (LC &#35;48) — same reverse-based logic extended to 2D.


50. Maximum Beauty of an Array After Applying Operation Medium

OnsiteSorting · Sliding Window · Binary SearchLeetCode: #2779

You can replace nums[i] with any value in [nums[i]-k, nums[i]+k]. Find the maximum length subsequence with all equal elements after the operations. Reported in Salesforce OA.

Input: nums = [4,6,1,2], k = 2
Output: 3

Input: nums = [1,1,1,1], k = 10
Output: 4

Approach: Each element can reach any value in [nums[i]-k, nums[i]+k]. Sort the array. Sliding window: maximum window where nums[right] - nums[left] ≤ 2k (all can be made equal). Window size is the answer. *Complexity: Time O(n log n) · Space O(1) Follow-up: Same problem where you can only increase values (not decrease) — use binary search for each element's window upper bound.


Preparation Tips

Salesforce interviews are heavily weighted toward arrays, strings, and hashing — master all sliding window, two-pointer, and hash map patterns. For tree problems, be ready to implement DFS and BFS both iteratively and recursively. The LLD round (AMTS) will almost certainly feature LRU Cache, Parking Lot, or Trie — practise these until you can implement them from scratch in 20 minutes. For the HLD round (MTS), think about Salesforce's core domain: millions of CRM contacts that must sync reliably. Data deduplication (Accounts Merge), event-driven notification pipelines, and consistent search indexing are favourite HLD topics. Always write clean code with meaningful variable names — Salesforce interviewers score code quality as a first-class signal.

Join our Telegram group for Salesforce interview experiences, OA question sets, and placement resources shared by students placed at Salesforce India.

Useful Resources