Data Structures & Algorithms Interview Questions

Review this list of 226 data structures & algorithms interview questions and answers verified by hiring managers and candidates.
  • Capital One logoAsked at Capital One 
    Software Engineer
    Data Structures & Algorithms
    +2 more
  • Adobe logoAsked at Adobe 
    +7

    "function findPrimes(n) { if (n < 2) return []; const primes = []; for (let i=2; i <= n; i++) { const half = Math.floor(i/2); let isPrime = true; for (let prime of primes) { if (i % prime === 0) { isPrime = false; break; } } if (isPrime) { primes.push(i); } } return primes; } `"

    Tiago R. - "function findPrimes(n) { if (n < 2) return []; const primes = []; for (let i=2; i <= n; i++) { const half = Math.floor(i/2); let isPrime = true; for (let prime of primes) { if (i % prime === 0) { isPrime = false; break; } } if (isPrime) { primes.push(i); } } return primes; } `"See full answer

    Data Engineer
    Data Structures & Algorithms
    +4 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Given an nxn grid of 1s and 0s, return the number of islands in the input.'
    +9

    " from typing import List def getnumberof_islands(binaryMatrix: List[List[int]]) -> int: if not binaryMatrix: return 0 rows = len(binaryMatrix) cols = len(binaryMatrix[0]) islands = 0 for r in range(rows): for c in range(cols): if binaryMatrixr == 1: islands += 1 dfs(binaryMatrix, r, c) return islands def dfs(grid, r, c): if ( r = len(grid) "

    Rick E. - " from typing import List def getnumberof_islands(binaryMatrix: List[List[int]]) -> int: if not binaryMatrix: return 0 rows = len(binaryMatrix) cols = len(binaryMatrix[0]) islands = 0 for r in range(rows): for c in range(cols): if binaryMatrixr == 1: islands += 1 dfs(binaryMatrix, r, c) return islands def dfs(grid, r, c): if ( r = len(grid) "See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Find a triplet in an array with a given sum.'
    +5

    "from typing import List def three_sum(nums: List[int]) -> List[List[int]]: nums.sort() triplets = set() for i in range(len(nums) - 2): firstNum = nums[i] l = i + 1 r = len(nums) - 1 while l 0: r -= 1 elif potentialSum < 0: l += 1 "

    Anonymous Roadrunner - "from typing import List def three_sum(nums: List[int]) -> List[List[int]]: nums.sort() triplets = set() for i in range(len(nums) - 2): firstNum = nums[i] l = i + 1 r = len(nums) - 1 while l 0: r -= 1 elif potentialSum < 0: l += 1 "See full answer

    Software Engineer
    Data Structures & Algorithms
    +3 more
  • "Let’s say the matrix is m x n (i.e., m rows and n columns). Start from the top-right corner of the matrix. Move left if you see a 1. Move down if you see a 0. Keep track of the row index where you last saw the leftmost 1 — that row has the most 1s. public class MaxOnesRow { public static int rowWithMostOnes(int matrix) { int rows = matrix.length; int cols = matrix[0].length; int maxRowIndex = -1; int j = cols - 1; /"

    Khushbu R. - "Let’s say the matrix is m x n (i.e., m rows and n columns). Start from the top-right corner of the matrix. Move left if you see a 1. Move down if you see a 0. Keep track of the row index where you last saw the leftmost 1 — that row has the most 1s. public class MaxOnesRow { public static int rowWithMostOnes(int matrix) { int rows = matrix.length; int cols = matrix[0].length; int maxRowIndex = -1; int j = cols - 1; /"See full answer

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

  • Meta (Facebook) logoAsked at Meta (Facebook) 

    "Problem: Given a modified binary tree, where each node also has a pointer to it's parent, find the first common ancestor of two nodes. Answer: As it happens, the structure that we're looking at is actually a linked list (one pointer up), so the problem is identical to trying to find if two linked lists share a common node. How this works is by stacking the two chains of nodes together so they're the same length. chain1 = node1 chain2= node2 while True: chain1 = chain1.next chain2=chain"

    Michael B. - "Problem: Given a modified binary tree, where each node also has a pointer to it's parent, find the first common ancestor of two nodes. Answer: As it happens, the structure that we're looking at is actually a linked list (one pointer up), so the problem is identical to trying to find if two linked lists share a common node. How this works is by stacking the two chains of nodes together so they're the same length. chain1 = node1 chain2= node2 while True: chain1 = chain1.next chain2=chain"See full answer

    Machine Learning Engineer
    Data Structures & Algorithms
    +1 more
  • Meta (Facebook) logoAsked at Meta (Facebook) 
    +1

    "my answer: void* memcpy(void* dest, const void* src, size_t n) { unsigned char* uDest = static_cast(dest); const unsigned char* ucSrc = static_cast(src); for(size_t i= 0; i(dest); const unsigned c"

    Srihitha J. - "my answer: void* memcpy(void* dest, const void* src, size_t n) { unsigned char* uDest = static_cast(dest); const unsigned char* ucSrc = static_cast(src); for(size_t i= 0; i(dest); const unsigned c"See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Machine Learning Engineer
    Data Structures & Algorithms
    +3 more
  • Google logoAsked at Google 

    "Yes, I need to compare the first half of the first string with the reverse order of the second half of the second string. Repeat this process to the first half of the second string and the second half of the first string."

    Noor M. - "Yes, I need to compare the first half of the first string with the reverse order of the second half of the second string. Repeat this process to the first half of the second string and the second half of the first string."See full answer

    Machine Learning Engineer
    Data Structures & Algorithms
    +1 more
  • +12

    " from typing import Dict, List, Optional def max_profit(prices: Dict[str, int]) -> Optional[List[str]]: pass # your code goes here max = [None, 0] min = [None, float("inf")] for city, price in prices.items(): if price > max[1]: max[0], max[1] = city, price if price 0: return [min[0], max[0]] return None debug your code below prices = {'"

    Rick E. - " from typing import Dict, List, Optional def max_profit(prices: Dict[str, int]) -> Optional[List[str]]: pass # your code goes here max = [None, 0] min = [None, float("inf")] for city, price in prices.items(): if price > max[1]: max[0], max[1] = city, price if price 0: return [min[0], max[0]] return None debug your code below prices = {'"See full answer

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

    "const ops = { '+': (a, b) => a+b, '-': (a, b) => a-b, '/': (a, b) => a/b, '': (a, b) => ab, }; function calc(expr) { // Search for + or - for (let i=expr.length-1; i >= 0; i--) { const char = expr.charAt(i); if (['+', '-'].includes(char)) { return opschar), calc(expr.slice(i+1))); } } // Search for / or * for (let i=expr.length-1; i >= 0; i--) { const char = expr.charAt(i); if"

    Tiago R. - "const ops = { '+': (a, b) => a+b, '-': (a, b) => a-b, '/': (a, b) => a/b, '': (a, b) => ab, }; function calc(expr) { // Search for + or - for (let i=expr.length-1; i >= 0; i--) { const char = expr.charAt(i); if (['+', '-'].includes(char)) { return opschar), calc(expr.slice(i+1))); } } // Search for / or * for (let i=expr.length-1; i >= 0; i--) { const char = expr.charAt(i); if"See full answer

    Software Engineer
    Data Structures & Algorithms
    +3 more
  • Apple logoAsked at Apple 
    +8

    "class ListNode: def init(self, val=0, next=None): self.val = val self.next = next def has_cycle(head: ListNode) -> bool: slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False debug your code below node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) creates a linked list with a cycle: 1 -> 2 -> 3 -> 4"

    Anonymous Roadrunner - "class ListNode: def init(self, val=0, next=None): self.val = val self.next = next def has_cycle(head: ListNode) -> bool: slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False debug your code below node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) creates a linked list with a cycle: 1 -> 2 -> 3 -> 4"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • "Here is my first shot at it. Please excuse formatting. To find the maximum depth of the dependencies given a list of nodes, each having a unique string id and a list of subnodes it depends on, you can perform a depth-first search (DFS) to traverse the dependency graph. Here's how you can implement this: Represent the nodes and their dependencies using a dictionary. Perform a DFS on each node to find the maximum depth of the dependencies. Keep track of the maximum depth encountered dur"

    Tes d H. - "Here is my first shot at it. Please excuse formatting. To find the maximum depth of the dependencies given a list of nodes, each having a unique string id and a list of subnodes it depends on, you can perform a depth-first search (DFS) to traverse the dependency graph. Here's how you can implement this: Represent the nodes and their dependencies using a dictionary. Perform a DFS on each node to find the maximum depth of the dependencies. Keep track of the maximum depth encountered dur"See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Given stock prices for the next n days, how can you maximize your profit by buying or selling one share per day?'
    +9

    "from typing import List def maxprofitgreedy(stock_prices: List[int]) -> int: l=0 # buying r=1 # selling max_profit=0 while rstock_prices[l]: profit=stockprices[r]-stockprices[l] maxprofit=max(maxprofit,profit) else: l=r r+=1 return max_profit debug your code below print(maxprofitgreedy([7, 1, 5, 3, 6, 4])) `"

    Prajwal M. - "from typing import List def maxprofitgreedy(stock_prices: List[int]) -> int: l=0 # buying r=1 # selling max_profit=0 while rstock_prices[l]: profit=stockprices[r]-stockprices[l] maxprofit=max(maxprofit,profit) else: l=r r+=1 return max_profit debug your code below print(maxprofitgreedy([7, 1, 5, 3, 6, 4])) `"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • "It depends on the size of the dataset. You want enough samples in both the testing, training and evaluation sets. If there is enough data, 70/20/10 is a good split"

    Jasmine Y. - "It depends on the size of the dataset. You want enough samples in both the testing, training and evaluation sets. If there is enough data, 70/20/10 is a good split"See full answer

    Data Structures & Algorithms
    Coding
  • Accenture logoAsked at Accenture 

    "NA"

    Gaddipati V. - "NA"See full answer

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

    "def split_count(s): return 2**(len(s)-1) `"

    Steve M. - "def split_count(s): return 2**(len(s)-1) `"See full answer

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

    " import pandas as pd def findaveragedistance(gps_data: pd.DataFrame) -> pd.DataFrame: #0. IMPORTANT: get the unordered pairs gpsdata['city1']=gpsdata[['origin','destination']].min(axis=1) gpsdata['city2']=gpsdata[['origin','destination']].max(axis=1) #1. get the mean distance by cities avgdistance=gpsdata.groupby(['city1','city2'], as_index=False)['distance'].mean().round(2) avgdistance.rename(columns={'distance':"averagedistance"}, inplace=True) "

    Sean L. - " import pandas as pd def findaveragedistance(gps_data: pd.DataFrame) -> pd.DataFrame: #0. IMPORTANT: get the unordered pairs gpsdata['city1']=gpsdata[['origin','destination']].min(axis=1) gpsdata['city2']=gpsdata[['origin','destination']].max(axis=1) #1. get the mean distance by cities avgdistance=gpsdata.groupby(['city1','city2'], as_index=False)['distance'].mean().round(2) avgdistance.rename(columns={'distance':"averagedistance"}, inplace=True) "See full answer

    Data Structures & Algorithms
    Coding
    +1 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Generate Parentheses'
    +5

    "function generateParentheses(n) { if (n < 1) { return []; } if (n === 1) { return ["()"]; } const combinations = new Set(); let previousCombinations = generateParentheses(n-1); for (let prev of previousCombinations) { for (let i=0; i < prev.length; i++) { combinations.add(prev.slice(0, i+1) + "()" + prev.slice(i+1)); } } return [...combinations]; } `"

    Tiago R. - "function generateParentheses(n) { if (n < 1) { return []; } if (n === 1) { return ["()"]; } const combinations = new Set(); let previousCombinations = generateParentheses(n-1); for (let prev of previousCombinations) { for (let i=0; i < prev.length; i++) { combinations.add(prev.slice(0, i+1) + "()" + prev.slice(i+1)); } } return [...combinations]; } `"See full answer

    Software Engineer
    Data Structures & Algorithms
    +3 more
  • Adobe logoAsked at Adobe 
    Data Engineer
    Data Structures & Algorithms
    +4 more
Showing 61-80 of 226