Data Structures & Algorithms Interview Questions

Review this list of 65 data structures & algorithms interview questions and answers verified by hiring managers and candidates.
  • +9

    "function spiralCopy(inputMatrix) { if (inputMatrix.length === 1) return inputMatrix[0]; let lowerY = 0; let upperY = inputMatrix.length-1; let lowerX = 0; let upperX = inputMatrix[0].length-1; const output = []; while (true) { if (lowerX > upperX) break; for (let x = lowerX; x upperY) break; for (let y = lowerY; y <= upperY; y++) { output.push(inputMatrix[y][u"

    Tiago R. - "function spiralCopy(inputMatrix) { if (inputMatrix.length === 1) return inputMatrix[0]; let lowerY = 0; let upperY = inputMatrix.length-1; let lowerX = 0; let upperX = inputMatrix[0].length-1; const output = []; while (true) { if (lowerX > upperX) break; for (let x = lowerX; x upperY) break; for (let y = lowerY; y <= upperY; y++) { output.push(inputMatrix[y][u"See full answer

    Data Structures & Algorithms
    Coding
  • +5

    "function knapsack(weights, values, cap) { const indicesByValue = Object.keys(weights).map(weight => parseInt(weight)); indicesByValue.sort((a, b) => values[b]-values[a]); const steps = new Map(); function knapsackStep(cap, sack) { if (steps.has(sack)) { return steps.get(sack); } let maxOutput = 0; for (let index of indicesByValue) { if (!sack.has(index) && weights[index] <= cap) { maxOutput ="

    Tiago R. - "function knapsack(weights, values, cap) { const indicesByValue = Object.keys(weights).map(weight => parseInt(weight)); indicesByValue.sort((a, b) => values[b]-values[a]); const steps = new Map(); function knapsackStep(cap, sack) { if (steps.has(sack)) { return steps.get(sack); } let maxOutput = 0; for (let index of indicesByValue) { if (!sack.has(index) && weights[index] <= cap) { maxOutput ="See full answer

    Software Engineer
    Data Structures & Algorithms
    +2 more
  • Meta (Facebook) logoAsked at Meta (Facebook) 
    Video answer for 'Sort a doubly linked list using merge sort.'
    +4

    "function merge(L1, L2) { let L3 = { data: null, next: null }; let prev = L3; while (L1 != null || L2 != null) { if (L1 == null) { prev.next = L2; L2 = L2.next; } else if (L2 == null) { prev.next = L1; L1 = L1.next; } else if (L1.data < L2.data) { prev.next = L1; L1 = L1.next; } else { prev.next = L2; L2 = L2.next; } prev = prev.next; } return L3.next; }"

    Ugo C. - "function merge(L1, L2) { let L3 = { data: null, next: null }; let prev = L3; while (L1 != null || L2 != null) { if (L1 == null) { prev.next = L2; L2 = L2.next; } else if (L2 == null) { prev.next = L1; L1 = L1.next; } else if (L1.data < L2.data) { prev.next = L1; L1 = L1.next; } else { prev.next = L2; L2 = L2.next; } prev = prev.next; } return L3.next; }"See full answer

    Data Structures & Algorithms
    Coding
    +1 more
  • Spotify logoAsked at Spotify 

    Balanced Tree

    IDE
    Medium
    +5

    "function visitChildren(node) { let leftSubtreeHeight = 0; let rightSubtreeHeight = 0; let isChildrenBalanced = true; if (node.left) { const { isBalanced, height } = visitChildren(node.left); isChildrenBalanced = isChildrenBalanced && isBalanced; leftSubtreeHeight += height + 1; } if (isChildrenBalanced && node.right) { const { isBalanced, height } = visitChildren(node.right); isChildrenBalanced = isChildrenBalanced && isBalan"

    Tiago R. - "function visitChildren(node) { let leftSubtreeHeight = 0; let rightSubtreeHeight = 0; let isChildrenBalanced = true; if (node.left) { const { isBalanced, height } = visitChildren(node.left); isChildrenBalanced = isChildrenBalanced && isBalanced; leftSubtreeHeight += height + 1; } if (isChildrenBalanced && node.right) { const { isBalanced, height } = visitChildren(node.right); isChildrenBalanced = isChildrenBalanced && isBalan"See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • +6

    "Node findInOrderSuccessor(Node inputNode) { // your code goes here int key = inputNode.key; Node currentNode = this.root; Node succ = null; while(currentNode != null){ if(currentNode.key > key){ succ = currentNode; currentNode = currentNode.left; } else { currentNode = currentNode.right; } } return succ; } `"

    Sam J. - "Node findInOrderSuccessor(Node inputNode) { // your code goes here int key = inputNode.key; Node currentNode = this.root; Node succ = null; while(currentNode != null){ if(currentNode.key > key){ succ = currentNode; currentNode = currentNode.left; } else { currentNode = currentNode.right; } } return succ; } `"See full answer

    Data Structures & Algorithms
    Coding
  • 🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.

  • Adobe logoAsked at Adobe 
    +5

    "bool isValidBST(TreeNode* root, long min = LONGMIN, long max = LONGMAX){ if (root == NULL) return true; if (root->val val >= max) return false; return isValidBST(root->left, min, root->val) && isValidBST(root->right, root->val, max); } `"

    Alvaro R. - "bool isValidBST(TreeNode* root, long min = LONGMIN, long max = LONGMAX){ if (root == NULL) return true; if (root->val val >= max) return false; return isValidBST(root->left, min, root->val) && isValidBST(root->right, root->val, max); } `"See full answer

    Data Engineer
    Data Structures & Algorithms
    +4 more
  • Microsoft logoAsked at Microsoft 
    Video answer for 'Find the number of rotations in a circularly sorted array.'
    +8

    "function countRotations(arr, low, high) { if (high low && arr[mid] arr[mid]) { return countRotations(arr, low, mid - 1); } return countRotations(arr, mid + 1, high); } "

    Ugo C. - "function countRotations(arr, low, high) { if (high low && arr[mid] arr[mid]) { return countRotations(arr, low, mid - 1); } return countRotations(arr, mid + 1, high); } "See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Sales Path

    IDE
    Medium
    +6

    "def getcheapestcost(rootNode): \# need to do DFS for each branch \# but this can be done recursively n = len(rootNode.children) if n == 0: return 0 else: min_cost = float('inf') for i in range(len(n)): tempcost = getcheapest_cost(rootNode.children[i]) if (tempcost < mincost): mincost = tempcost return min_cost + rootNode.cost \# A node class Node: \# Constructor to create a new node def init\(self, cost): self.cost = cost self.children = [] self.parent = None"

    Anonymous Owl - "def getcheapestcost(rootNode): \# need to do DFS for each branch \# but this can be done recursively n = len(rootNode.children) if n == 0: return 0 else: min_cost = float('inf') for i in range(len(n)): tempcost = getcheapest_cost(rootNode.children[i]) if (tempcost < mincost): mincost = tempcost return min_cost + rootNode.cost \# A node class Node: \# Constructor to create a new node def init\(self, cost): self.cost = cost self.children = [] self.parent = None"See full answer

    Data Structures & Algorithms
    Coding
  • Apple logoAsked at Apple 
    +2

    "This could be done using two-pointer approach assuming array is sorted: left and right pointers. We need track two sums (left and right) as we move pointers. For moving pointers we will move left to right by 1 (increment) when right sum is greater. We will move right pointer to left by 1 (decrement) when left sum is greater. at some point we will either get the sum same and that's when we exit from the loop. 0-left will be one array and right-(n-1) will be another array. We are not going to mo"

    Bhaskar B. - "This could be done using two-pointer approach assuming array is sorted: left and right pointers. We need track two sums (left and right) as we move pointers. For moving pointers we will move left to right by 1 (increment) when right sum is greater. We will move right pointer to left by 1 (decrement) when left sum is greater. at some point we will either get the sum same and that's when we exit from the loop. 0-left will be one array and right-(n-1) will be another array. We are not going to mo"See full answer

    Software Engineer
    Data Structures & Algorithms
    +2 more
  • +7

    "I couldn't follow the solution offered here, but my solution seemed to pass 6/6 tests. Any feedback is welcome, thank you! def encrypt(word): en_word = "" for i in range(len(word)): if i == 0: en_word += chr(ord(word[0])+1) else: num = ord(word[i]) + ord(en_word[i-1]) while num > 122: num -= 26 en_word += chr(num) return en_word def decrypt(word): de_word = "" for i in range(len(word)): if i == 0: de_word += chr(ord(word[i]"

    Anonymous Armadillo - "I couldn't follow the solution offered here, but my solution seemed to pass 6/6 tests. Any feedback is welcome, thank you! def encrypt(word): en_word = "" for i in range(len(word)): if i == 0: en_word += chr(ord(word[0])+1) else: num = ord(word[i]) + ord(en_word[i-1]) while num > 122: num -= 26 en_word += chr(num) return en_word def decrypt(word): de_word = "" for i in range(len(word)): if i == 0: de_word += chr(ord(word[i]"See full answer

    Data Structures & Algorithms
    Coding
  • Apple logoAsked at Apple 

    "class TrieNode { constructor() { this.children = {}; this.isEndOfWord = false; } } class Trie { constructor() { this.root = new TrieNode(); } insert(word) { let node = this.root; for (const char of word) { if (!node.children[char]) { node.children[char] = new TrieNode(); } node = node.children[char]; } node.isEndOfWord = true; } search(word) { l"

    Tiago R. - "class TrieNode { constructor() { this.children = {}; this.isEndOfWord = false; } } class Trie { constructor() { this.root = new TrieNode(); } insert(word) { let node = this.root; for (const char of word) { if (!node.children[char]) { node.children[char] = new TrieNode(); } node = node.children[char]; } node.isEndOfWord = true; } search(word) { l"See full answer

    Data Engineer
    Data Structures & Algorithms
    +3 more
  • +6

    "Good Question, but I would've marked this as medium not hard difficulty, since it's just a straightforward traversal."

    Ahmed A. - "Good Question, but I would've marked this as medium not hard difficulty, since it's just a straightforward traversal."See full answer

    Data Structures & Algorithms
    Coding
  • Adobe logoAsked at Adobe 
    +17

    " O(n) time, O(1) space from typing import List def maxsubarraysum(nums: List[int]) -> int: if len(nums) == 0: return 0 maxsum = currsum = nums[0] for i in range(1, len(nums)): currsum = max(currsum + nums[i], nums[i]) maxsum = max(currsum, max_sum) return max_sum debug your code below print(maxsubarraysum([-1, 2, -3, 4])) `"

    Rick E. - " O(n) time, O(1) space from typing import List def maxsubarraysum(nums: List[int]) -> int: if len(nums) == 0: return 0 maxsum = currsum = nums[0] for i in range(1, len(nums)): currsum = max(currsum + nums[i], nums[i]) maxsum = max(currsum, max_sum) return max_sum debug your code below print(maxsubarraysum([-1, 2, -3, 4])) `"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • LinkedIn logoAsked at LinkedIn 
    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Adobe logoAsked at Adobe 

    Permutations

    IDE
    Medium

    "function permute(nums) { if (nums.length <= 1) { return [nums]; } const prevPermutations = permute(nums.slice(0, nums.length-1)); const currentNum = nums[nums.length-1]; const permutations = new Set(); for (let prev of prevPermutations) { for (let i=0; i < prev.length; i++) { permutations.add([...prev.slice(0, i), currentNum, ...prev.slice(i)]); } permutations.add([...prev, currentNum]); } return [...permutations]"

    Tiago R. - "function permute(nums) { if (nums.length <= 1) { return [nums]; } const prevPermutations = permute(nums.slice(0, nums.length-1)); const currentNum = nums[nums.length-1]; const permutations = new Set(); for (let prev of prevPermutations) { for (let i=0; i < prev.length; i++) { permutations.add([...prev.slice(0, i), currentNum, ...prev.slice(i)]); } permutations.add([...prev, currentNum]); } return [...permutations]"See full answer

    Software Engineer
    Data Structures & Algorithms
    +3 more
  • +3

    "def flatten_dictionary(dictionary): \# return a flattened dictionary - int/string/another dictionary values \# if the key is empty, exclude from the output \# concat using a "." btwn them \# add to res which is { "key.a.b.etc": "value" } \# iterate through the key value pairs \# while there is a key value pair in the value \# continue going through that, until the value is an int/string flatDic = {} flatDicHelper("", dictionary, flatDic) print(flatDic) return flatDic def flatDicHelper(initialKey"

    Anonymous Owl - "def flatten_dictionary(dictionary): \# return a flattened dictionary - int/string/another dictionary values \# if the key is empty, exclude from the output \# concat using a "." btwn them \# add to res which is { "key.a.b.etc": "value" } \# iterate through the key value pairs \# while there is a key value pair in the value \# continue going through that, until the value is an int/string flatDic = {} flatDicHelper("", dictionary, flatDic) print(flatDic) return flatDic def flatDicHelper(initialKey"See full answer

    Data Structures & Algorithms
    Coding
  • +4

    "function getDifferentNumber(arr) { // your code goes here const n = arr.length; //Define Max Integer const MAX_INT = Math.pow(2, 31) - 1; //Coppy arr to arr1 then sort arr1. const arr1 = arr; arr1.sort(function(a,b) {return a -b}); // Put arr1 in Set to optimize lo const uniqueSet = new Set(arr1); console.log(uniqueSet); // Check for the smallest nonnegative integer not in the array for (let i = 0; i < n; i++) { if (!uniqueSet.has(i)) { return i; } } if(n<MAX_INT) return n+1; else return -1; }"

    Anonymous Hare - "function getDifferentNumber(arr) { // your code goes here const n = arr.length; //Define Max Integer const MAX_INT = Math.pow(2, 31) - 1; //Coppy arr to arr1 then sort arr1. const arr1 = arr; arr1.sort(function(a,b) {return a -b}); // Put arr1 in Set to optimize lo const uniqueSet = new Set(arr1); console.log(uniqueSet); // Check for the smallest nonnegative integer not in the array for (let i = 0; i < n; i++) { if (!uniqueSet.has(i)) { return i; } } if(n<MAX_INT) return n+1; else return -1; }"See full answer

    Data Structures & Algorithms
    Coding
  • +4

    "Using a DFS approach, computing all the distances from typing import List from collections import deque def shortestCellPath(grid: List[List[int]], sr: int, sc: int, tr: int, tc: int) -> int: if sr == tr and sc == tc: return 0 nRows = len(grid) nCols = len(grid[0]) distances = [] stack = deque([(sr, sc, 0)]) visitedSet = set() while stack: nodeR, nodeC, nodeDist = stack.pop() if gridnodeR == 0 or (nodeR, nodeC) in visited"

    Gabriele G. - "Using a DFS approach, computing all the distances from typing import List from collections import deque def shortestCellPath(grid: List[List[int]], sr: int, sc: int, tr: int, tc: int) -> int: if sr == tr and sc == tc: return 0 nRows = len(grid) nCols = len(grid[0]) distances = [] stack = deque([(sr, sc, 0)]) visitedSet = set() while stack: nodeR, nodeC, nodeDist = stack.pop() if gridnodeR == 0 or (nodeR, nodeC) in visited"See full answer

    Data Structures & Algorithms
    Coding
  • Adobe logoAsked at Adobe 

    "static boolean sudokuSolve(char board) { return sudokuSolve(board, 0, 0); } static boolean sudokuSolve(char board, int r, int c) { if(c>=board[0].length) { r=r+1; c=0; } if(r>=board.length) return true; if(boardr=='.') { for(int num=1; num<=9; num++) { boardr=(char)('0' + num); if(isValidPosition(board, r, c)) { if(sudokuSolve(board, r, c+1)) return true; } boardr='.'; } } else { return sudokuSolve(board, r, c+1); } return false; } static boolean isValidPosition(char b"

    Divya R. - "static boolean sudokuSolve(char board) { return sudokuSolve(board, 0, 0); } static boolean sudokuSolve(char board, int r, int c) { if(c>=board[0].length) { r=r+1; c=0; } if(r>=board.length) return true; if(boardr=='.') { for(int num=1; num<=9; num++) { boardr=(char)('0' + num); if(isValidPosition(board, r, c)) { if(sudokuSolve(board, r, c+1)) return true; } boardr='.'; } } else { return sudokuSolve(board, r, c+1); } return false; } static boolean isValidPosition(char b"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • Adobe logoAsked at Adobe 
    +7

    "from typing import List def traprainwater(height: List[int]) -> int: if not height: return 0 l, r = 0, len(height) - 1 leftMax, rightMax = height[l], height[r] res = 0 while l < r: if leftMax < rightMax: l += 1 leftMax = max(leftMax, height[l]) res += leftMax - height[l] else: r -= 1 rightMax = max(rightMax, height[r]) "

    Anonymous Roadrunner - "from typing import List def traprainwater(height: List[int]) -> int: if not height: return 0 l, r = 0, len(height) - 1 leftMax, rightMax = height[l], height[r] res = 0 while l < r: if leftMax < rightMax: l += 1 leftMax = max(leftMax, height[l]) res += leftMax - height[l] else: r -= 1 rightMax = max(rightMax, height[r]) "See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
Showing 41-60 of 65