Data Structures & Algorithms Interview Questions

Review this list of 226 data structures & algorithms interview questions and answers verified by hiring managers and candidates.
  • Apple logoAsked at Apple 

    "First of all, stack and heap memory are abstraction on top of the hardware by the compiler. The hardware is not aware of stack and heap memory. There is only a single piece of memory that a program has access to. The compiler creates the concepts of stack and heap memory to run the programs efficiently. Programs use stack memory to store local variables and a few important register values such as frame pointer and return address for program counter. This makes it easier for the compiler to gene"

    Stanley Y. - "First of all, stack and heap memory are abstraction on top of the hardware by the compiler. The hardware is not aware of stack and heap memory. There is only a single piece of memory that a program has access to. The compiler creates the concepts of stack and heap memory to run the programs efficiently. Programs use stack memory to store local variables and a few important register values such as frame pointer and return address for program counter. This makes it easier for the compiler to gene"See full answer

    Software Engineer
    Data Structures & Algorithms
    +2 more
  • Meta (Facebook) logoAsked at Meta (Facebook) 

    "Problem: Given an input string txt consisting of alphanumeric characters and the parentheses characters '(' & ')', write a function which removes the minimum number of characters to return a version of the string with properly balanced parenthesis. Answer: You can do this with a counter. Psuedo-Python Start with counter = 0 output = [] Iterate through the string, every time you encounter a '(', increment the counter. Add the character to the output. If you encounter a ')', decrement the coun"

    Michael B. - "Problem: Given an input string txt consisting of alphanumeric characters and the parentheses characters '(' & ')', write a function which removes the minimum number of characters to return a version of the string with properly balanced parenthesis. Answer: You can do this with a counter. Psuedo-Python Start with counter = 0 output = [] Iterate through the string, every time you encounter a '(', increment the counter. Add the character to the output. If you encounter a ')', decrement the coun"See full answer

    Machine Learning Engineer
    Data Structures & Algorithms
    +1 more
  • "Write a function which Caesar ciphers all the strings so that the first character is "a". Use ascii code points and the modulo operator to do this. Use this function to create a hashmap between each string and the CC-a string. Then go through each key:value pair in the hashmap, and use the CC-a ciphered value as the key in a new defaultdict(list), adding the original string to the value field in the output."

    Michael B. - "Write a function which Caesar ciphers all the strings so that the first character is "a". Use ascii code points and the modulo operator to do this. Use this function to create a hashmap between each string and the CC-a string. Then go through each key:value pair in the hashmap, and use the CC-a ciphered value as the key in a new defaultdict(list), adding the original string to the value field in the output."See full answer

    Machine Learning Engineer
    Data Structures & Algorithms
    +1 more
  • Adobe logoAsked at Adobe 
    +6

    " function climbStairs(n) { // 4 iterations of Dynamic Programming solutions: // Step 1: Recursive: // if (n <= 2) return n // return climbStairs(n-1) + climbStairs(n-2) // Step 2: Top-down Memoization // const memo = {0:0, 1:1, 2:2} // function f(x) { // if (x in memo) return memo[x] // memo[x] = f(x-1) + f(x-2) // return memo[x] // } // return f(n) // Step 3: Bottom-up Tabulation // const tab = [0,1,2] // f"

    Matthew K. - " function climbStairs(n) { // 4 iterations of Dynamic Programming solutions: // Step 1: Recursive: // if (n <= 2) return n // return climbStairs(n-1) + climbStairs(n-2) // Step 2: Top-down Memoization // const memo = {0:0, 1:1, 2:2} // function f(x) { // if (x in memo) return memo[x] // memo[x] = f(x-1) + f(x-2) // return memo[x] // } // return f(n) // Step 3: Bottom-up Tabulation // const tab = [0,1,2] // f"See full answer

    Data Engineer
    Data Structures & Algorithms
    +3 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Move all zeros to the end of an array.'
    +39

    "Initialize left pointer: Set a left pointer left to 0. Iterate through the array: Iterate through the array from left to right. If the current element is not 0, swap it with the element at the left pointer and increment left. Time complexity: O(n). The loop iterates through the entire array once, making it linear time. Space complexity: O(1). The algorithm operates in-place, modifying the input array directly without using additional data structures. "

    Avon T. - "Initialize left pointer: Set a left pointer left to 0. Iterate through the array: Iterate through the array from left to right. If the current element is not 0, swap it with the element at the left pointer and increment left. Time complexity: O(n). The loop iterates through the entire array once, making it linear time. Space complexity: O(1). The algorithm operates in-place, modifying the input array directly without using additional data structures. "See full answer

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

  • Amazon logoAsked at Amazon 
    +7

    "Without using a recursive approach, one can perform a post-order traversal by removing the parent nodes from the stack only if children were visited: def diameterOfTree(root): if root is None: return 0 diameter = 0 stack = deque([[root, False]]) # (node, visited) node_heights = {} while stack: curr_node, visited = stack[-1] if visited: heightleft = nodeheights.get(curr_node.left, 0) heightright = nodehe"

    Gabriele G. - "Without using a recursive approach, one can perform a post-order traversal by removing the parent nodes from the stack only if children were visited: def diameterOfTree(root): if root is None: return 0 diameter = 0 stack = deque([[root, False]]) # (node, visited) node_heights = {} while stack: curr_node, visited = stack[-1] if visited: heightleft = nodeheights.get(curr_node.left, 0) heightright = nodehe"See full answer

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

    "There is a faster approach that solves the problem in O(n) time: def find_duplicates(arr1, arr2): arr1 = set(arr1) res = [] for num in arr2: if num in arr1: res.append(num) return res `"

    Victor H. - "There is a faster approach that solves the problem in O(n) time: def find_duplicates(arr1, arr2): arr1 = set(arr1) res = [] for num in arr2: if num in arr1: res.append(num) return res `"See full answer

    Data Engineer
    Data Structures & Algorithms
    +2 more
  • Google logoAsked at Google 
    Video answer for 'Write functions to serialize and deserialize a list of strings.'
    +4

    "function serialize(list) { for (let i=0; i 0xFFFF) { throw new Exception(String ${list[i]} is too long!); } const prefix = String.fromCharCode(length); list[i] = ${prefix}${list[i]}; console.log(list[i]) } return list.join(''); } function deserialize(s) { let i=0; const length = s.length; const output = []; while (i < length) { "

    Tiago R. - "function serialize(list) { for (let i=0; i 0xFFFF) { throw new Exception(String ${list[i]} is too long!); } const prefix = String.fromCharCode(length); list[i] = ${prefix}${list[i]}; console.log(list[i]) } return list.join(''); } function deserialize(s) { let i=0; const length = s.length; const output = []; while (i < length) { "See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Microsoft logoAsked at Microsoft 

    "You are given a string S and a number K as input, and your task is to print S to console output considering that, at most, you can print K characters per line. Example: S = "abracadabra sample" K = 11 Output: abracadabra sample Note that this problem requires the interviewee gather extra requirements from the interviewer (e.g. do we care about multiple white spaces? what if the length of a word is greater than K, ...)"

    B. T. - "You are given a string S and a number K as input, and your task is to print S to console output considering that, at most, you can print K characters per line. Example: S = "abracadabra sample" K = 11 Output: abracadabra sample Note that this problem requires the interviewee gather extra requirements from the interviewer (e.g. do we care about multiple white spaces? what if the length of a word is greater than K, ...)"See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Amazon logoAsked at Amazon 

    "Was the statement very similar to the leetcode or was it changed and only the main idea remained?"

    Anonymous Wombat - "Was the statement very similar to the leetcode or was it changed and only the main idea remained?"See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Given the root of a binary tree of integers, return the maximum path sum.'

    "\# Definition for a binary tree node. class TreeNode: def init(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: self.max_sum = float('-inf')"

    Jerry O. - "\# Definition for a binary tree node. class TreeNode: def init(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: self.max_sum = float('-inf')"See full answer

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

    "Count items between indices within compartments compartments are delineated by by: '|' items are identified by: '*' input_inventory = "*||||" inputstartidxs = [1, 4, 6] inputendidxs = [9, 5, 8] expected_output = [3, 0, 1] Explanation: "*||||" 0123456789... indices ++ + # within compartments ^ start_idx = 1 ^ end_idx = 9 -- - # within idxs but not within compartments "*||||" 0123456789... indices "

    Anonymous Unicorn - "Count items between indices within compartments compartments are delineated by by: '|' items are identified by: '*' input_inventory = "*||||" inputstartidxs = [1, 4, 6] inputendidxs = [9, 5, 8] expected_output = [3, 0, 1] Explanation: "*||||" 0123456789... indices ++ + # within compartments ^ start_idx = 1 ^ end_idx = 9 -- - # within idxs but not within compartments "*||||" 0123456789... indices "See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Goldman Sachs logoAsked at Goldman Sachs 
    +8

    "public static Integer[] findLargest(int[] input, int m) { if(input==null || input.length==0) return null; PriorityQueue minHeap=new PriorityQueue(); for(int i:input) { if(minHeap.size()(int)top){ minHeap.poll(); minHeap.add(i); } } } Integer[] res=minHeap.toArray(new Integer[0]); Arrays.sort(res); return res; }"

    Divya R. - "public static Integer[] findLargest(int[] input, int m) { if(input==null || input.length==0) return null; PriorityQueue minHeap=new PriorityQueue(); for(int i:input) { if(minHeap.size()(int)top){ minHeap.poll(); minHeap.add(i); } } } Integer[] res=minHeap.toArray(new Integer[0]); Arrays.sort(res); return res; }"See full answer

    Machine Learning Engineer
    Data Structures & Algorithms
    +2 more
  • +16

    "def friend_distance(friends, userA, userB): step = 0 total_neighs = set() llen = len(total_neighs) total_neighs.add(userB) while len(total_neighs)!=llen: s = set() step += 1 llen = len(total_neighs) for el in total_neighs: nes = neighbours(friends, userA, el) if userA in nes: return step for p in nes: s.add(p) for el in s: total_neighs.add(el) return -1 def neighbours(A,n1, n2): out = set() for i in range(len(A[n2])): if An2: out.add(i) return out"

    Batman X. - "def friend_distance(friends, userA, userB): step = 0 total_neighs = set() llen = len(total_neighs) total_neighs.add(userB) while len(total_neighs)!=llen: s = set() step += 1 llen = len(total_neighs) for el in total_neighs: nes = neighbours(friends, userA, el) if userA in nes: return step for p in nes: s.add(p) for el in s: total_neighs.add(el) return -1 def neighbours(A,n1, n2): out = set() for i in range(len(A[n2])): if An2: out.add(i) return out"See full answer

    Data Structures & Algorithms
    Coding
  • Meta (Facebook) logoAsked at Meta (Facebook) 

    "Merge Sort"

    Ankita G. - "Merge Sort"See full answer

    Data Engineer
    Data Structures & Algorithms
    +1 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Product of Array Except Self'
    +38

    "This is just a two line solve, I'm not sure why it's being made more complicated? function productExceptSelf(nums) { // your code goes here const product = nums.reduce((acc, val) => acc * val, 1); return nums.map(num => num === 0 ? 0 : Math.floor(product/num)); } `"

    Marc S. - "This is just a two line solve, I'm not sure why it's being made more complicated? function productExceptSelf(nums) { // your code goes here const product = nums.reduce((acc, val) => acc * val, 1); return nums.map(num => num === 0 ? 0 : Math.floor(product/num)); } `"See full answer

    Software Engineer
    Data Structures & Algorithms
    +3 more
  • Airbnb logoAsked at Airbnb 
    Software Engineer
    Data Structures & Algorithms
    +4 more
  • Adobe logoAsked at Adobe 
    Software Engineer
    Data Structures & Algorithms
    +4 more
  • +17

    "def find_first(array: List[int], num: int) -> int: lo = 0 hi = len(array)-1 while lo = num: hi = mid - 1 if lo == mid and array[mid] == num: return mid else: array[mid] < num lo = mid + 1 return -1 `"

    Gabriele G. - "def find_first(array: List[int], num: int) -> int: lo = 0 hi = len(array)-1 while lo = num: hi = mid - 1 if lo == mid and array[mid] == num: return mid else: array[mid] < num lo = mid + 1 return -1 `"See full answer

    Data Structures & Algorithms
    Coding
  • Amazon logoAsked at Amazon 
    +8

    "Questions to ask : Are there negative values in the input array? Interview : YES Will the product of two number fit into 32-bit Integer. If not, will it fit 64-bit Integer. If not, then is it safe to use Big Integer? Interview : let's worry only about 32 bit Integer What should we return if the input array is null or size (size of input array) is less than 2? Return 0 From above Information: General approach is as follows : a) Track smallest 2 elements in the array -> p"

    Rajendra D. - "Questions to ask : Are there negative values in the input array? Interview : YES Will the product of two number fit into 32-bit Integer. If not, will it fit 64-bit Integer. If not, then is it safe to use Big Integer? Interview : let's worry only about 32 bit Integer What should we return if the input array is null or size (size of input array) is less than 2? Return 0 From above Information: General approach is as follows : a) Track smallest 2 elements in the array -> p"See full answer

    Data Structures & Algorithms
    Coding
Showing 41-60 of 226