Data Structures & Algorithms Interview Questions

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

    "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
  • Adobe logoAsked at Adobe 
    Video answer for 'Product of Array Except Self'
    +39

    "from typing import List def productExceptSelf(nums: List[int]) -> List[int]: if len(nums) <= 1: raise Exception("nums must contain at least 2 items.") Initialize totalProduct to the first number in nums. Later, we will populate this as the product of ALL numbers in nums. totalProduct = nums[0] if nums[0] != 0 else 1 If there is more than 1 zero in nums, all products will end up zero. But if there's only 1 zero, there will be 1 nonzer"

    Gemma S. - "from typing import List def productExceptSelf(nums: List[int]) -> List[int]: if len(nums) <= 1: raise Exception("nums must contain at least 2 items.") Initialize totalProduct to the first number in nums. Later, we will populate this as the product of ALL numbers in nums. totalProduct = nums[0] if nums[0] != 0 else 1 If there is more than 1 zero in nums, all products will end up zero. But if there's only 1 zero, there will be 1 nonzer"See full answer

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

    "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
  • 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 
    +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
  • 🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.

  • 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
  • Apple logoAsked at Apple 
    +9

    "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
  • 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
  • +13

    " 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
  • Waymo logoAsked at Waymo 
    +3

    " 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 
    +37

    "#include // Naive method to find a pair in an array with a given sum void findPair(int nums[], int n, int target) { // consider each element except the last for (int i = 0; i < n - 1; i++) { // start from the i'th element until the last element for (int j = i + 1; j < n; j++) { // if the desired sum is found, print it if (nums[i] + nums[j] == target) { printf("Pair found (%d, %d)\n", nums[i], nums[j]); return; } } } // we reach here if the pair is not found printf("Pair not found"); } "

    Gundala tarun,cse2020 V. - "#include // Naive method to find a pair in an array with a given sum void findPair(int nums[], int n, int target) { // consider each element except the last for (int i = 0; i < n - 1; i++) { // start from the i'th element until the last element for (int j = i + 1; j < n; j++) { // if the desired sum is found, print it if (nums[i] + nums[j] == target) { printf("Pair found (%d, %d)\n", nums[i], nums[j]); return; } } } // we reach here if the pair is not found printf("Pair not found"); } "See full answer

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

    "import time class Task: def init\(self, description, interval=None): self.description = description self.interval = interval self.next_run = time.time() class SimpleTaskScheduler: def init\(self): self.tasks = [] def add_task(self, description, interval=None): self.tasks.append(Task(description, interval)) def run(self, duration=60): end_time = time.time() + duration while time.time() < end_time: curr"

    Yash N. - "import time class Task: def init\(self, description, interval=None): self.description = description self.interval = interval self.next_run = time.time() class SimpleTaskScheduler: def init\(self): self.tasks = [] def add_task(self, description, interval=None): self.tasks.append(Task(description, interval)) def run(self, duration=60): end_time = time.time() + duration while time.time() < end_time: curr"See full answer

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

    "Problem Statement: The Fibonacci sequence is defined as F(n) = F(n-1) + F(n-2) with F(0) = 1 and F(1) = 1. The solution is given in the problem statement itself. If the value of n = 0, return 1. If the value of n = 1, return 1. Otherwise, return the sum of data at (n - 1) and (n - 2). Explanation: The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. Java Solution: public static int fib(int n"

    Rishi G. - "Problem Statement: The Fibonacci sequence is defined as F(n) = F(n-1) + F(n-2) with F(0) = 1 and F(1) = 1. The solution is given in the problem statement itself. If the value of n = 0, return 1. If the value of n = 1, return 1. Otherwise, return the sum of data at (n - 1) and (n - 2). Explanation: The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. Java Solution: public static int fib(int n"See full answer

    Software Engineer
    Data Structures & Algorithms
    +2 more
  • Adobe logoAsked at Adobe 
    +3

    "function addChildren(root, val, inorder) { const rootInOrderIndex = inorder.indexOf(root.value); const childrenInOrderIndex = inorder.indexOf(val); if (childrenInOrderIndex < rootInOrderIndex) { if (!root.left) { root.left = new TreeNode(val); } else { addChildren(root.left, val, inorder); } } else { if (!root.right) { root.right = new TreeNode(val); } else { addChildren(root.right,"

    Tiago R. - "function addChildren(root, val, inorder) { const rootInOrderIndex = inorder.indexOf(root.value); const childrenInOrderIndex = inorder.indexOf(val); if (childrenInOrderIndex < rootInOrderIndex) { if (!root.left) { root.left = new TreeNode(val); } else { addChildren(root.left, val, inorder); } } else { if (!root.right) { root.right = new TreeNode(val); } else { addChildren(root.right,"See full answer

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

    "def check_byte(octet): _""" Checks if the given string \octet\ represents a valid byte (0-255). """_ Check for empty string if not octet: return False Check if the string has non-digit characters if not octet.isdigit(): return False Check for leading zeroes in multi-digit numbers if len(octet) > 1 and octet[0] == '0': return False Check if the integer value is between 0 and 255 return 0 <= int(octet) <= 255 def va"

    Robert W. - "def check_byte(octet): _""" Checks if the given string \octet\ represents a valid byte (0-255). """_ Check for empty string if not octet: return False Check if the string has non-digit characters if not octet.isdigit(): return False Check for leading zeroes in multi-digit numbers if len(octet) > 1 and octet[0] == '0': return False Check if the integer value is between 0 and 255 return 0 <= int(octet) <= 255 def va"See full answer

    Data Structures & Algorithms
    Coding
  • +11

    "function swap(arr, i, j) { const temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } function sortKMessedArray(arr, k) { for (let i=0; i < arr.length; i++) { for (let j=1; j <= k; j++) { if (arr[i+j] < arr[i]) { swap(arr, i, i+j); } } } return arr; } `"

    Tiago R. - "function swap(arr, i, j) { const temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } function sortKMessedArray(arr, k) { for (let i=0; i < arr.length; i++) { for (let j=1; j <= k; j++) { if (arr[i+j] < arr[i]) { swap(arr, i, i+j); } } } return arr; } `"See full answer

    Data Structures & Algorithms
    Coding
  • Adobe logoAsked at Adobe 
    Video answer for 'Merge k sorted linked lists.'
    +6

    "A much better solution than the one in the article, below: It looks like the ones writing articles here in Javascript do not understand the time/space complexity of javascript methods. shift, splice, sort, etc... In the solution article you have a shift and a sort being done inside a while, that is, the multiplication of Ns. My solution, below, iterates through the list once and then sorts it, separately. It´s O(N+Log(N)) class ListNode { constructor(val = 0, next = null) { th"

    Guilherme F. - "A much better solution than the one in the article, below: It looks like the ones writing articles here in Javascript do not understand the time/space complexity of javascript methods. shift, splice, sort, etc... In the solution article you have a shift and a sort being done inside a while, that is, the multiplication of Ns. My solution, below, iterates through the list once and then sorts it, separately. It´s O(N+Log(N)) class ListNode { constructor(val = 0, next = null) { th"See full answer

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

    "function areSentencesSimilar(sentence1, sentence2, similarPairs) { if (sentence1.length !== sentence2.length) return false; for (let i=0; i (w1 === word1 && !visited.has(w2)) || (w2 === word1 && !visited.has(w1))); if (!edge) { "

    Tiago R. - "function areSentencesSimilar(sentence1, sentence2, similarPairs) { if (sentence1.length !== sentence2.length) return false; for (let i=0; i (w1 === word1 && !visited.has(w2)) || (w2 === word1 && !visited.has(w1))); if (!edge) { "See full answer

    Software Engineer
    Data Structures & Algorithms
    +2 more
Showing 21-40 of 65