Coding Interview Questions

Review this list of 137 interview questions and answers verified by hiring managers and candidates.
  • Adobe logoAsked at Adobe 
    Video answer for 'Product of Array Except Self'
    +40

    "If 0's aren't a concern, couldn't we just multiply all numbers. and then divide product by each number in the list ? if there's more than one zero, then we just return an array of 0s if there's one zero, then we just replace 0 with product and rest 0s. what am i missing?"

    Sachin R. - "If 0's aren't a concern, couldn't we just multiply all numbers. and then divide product by each number in the list ? if there's more than one zero, then we just return an array of 0s if there's one zero, then we just replace 0 with product and rest 0s. what am i missing?"See full answer

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

    "SELECT items.item_category, SUM(orders.orderquantity) AS totalunitsorderedlast7days FROM orders JOIN items ON orders.itemid = items.itemid WHERE orders.order_date BETWEEN DATE('now', '-6 days') AND DATE('now') GROUP BY items.item_category `"

    Salome L. - "SELECT items.item_category, SUM(orders.orderquantity) AS totalunitsorderedlast7days FROM orders JOIN items ON orders.itemid = items.itemid WHERE orders.order_date BETWEEN DATE('now', '-6 days') AND DATE('now') GROUP BY items.item_category `"See full answer

    Coding
    SQL
  • +10

    "WITH discount AS ( SELECT name, type, CASE WHEN type = 'Electronic' THEN price * 0.90 WHEN type = 'Clothing' THEN price * 0.80 WHEN type = 'Grocery' THEN price * 0.95 WHEN type = 'Book' THEN price * 0.85 ELSE price END AS discounted_price FROM products ) SELECT name, type, ROUND(discountedprice, 2) AS discountedprice FROM discount; `"

    Salome L. - "WITH discount AS ( SELECT name, type, CASE WHEN type = 'Electronic' THEN price * 0.90 WHEN type = 'Clothing' THEN price * 0.80 WHEN type = 'Grocery' THEN price * 0.95 WHEN type = 'Book' THEN price * 0.85 ELSE price END AS discounted_price FROM products ) SELECT name, type, ROUND(discountedprice, 2) AS discountedprice FROM discount; `"See full answer

    Coding
    SQL
  • +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
  • Pinterest logoAsked at Pinterest 
    Video answer for 'Implement a k-nearest neighbors algorithm.'
    +3

    "Even more faster and vectorized version, using np.linalg.norm - to avoid loop and np.argpartition to select lowest k. We dont need to sort whole array - we need to be sure that first k elements are lower than the rest. import numpy as np def knn(Xtrain, ytrain, X_new, k): distances = np.linalg.norm(Xtrain - Xnew, axis=1) k_indices = np.argpartition(distances, k)[:k] # O(N) selection instead of O(N log N) sort return int(np.sum(ytrain[kindices]) > k / 2.0) `"

    Dinar M. - "Even more faster and vectorized version, using np.linalg.norm - to avoid loop and np.argpartition to select lowest k. We dont need to sort whole array - we need to be sure that first k elements are lower than the rest. import numpy as np def knn(Xtrain, ytrain, X_new, k): distances = np.linalg.norm(Xtrain - Xnew, axis=1) k_indices = np.argpartition(distances, k)[:k] # O(N) selection instead of O(N log N) sort return int(np.sum(ytrain[kindices]) > k / 2.0) `"See full answer

    Machine Learning Engineer
    Coding
    +1 more
  • 🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.

  • +3

    "Order the result in descending month is not applied in the solution"

    Alina G. - "Order the result in descending month is not applied in the solution"See full answer

    Coding
    SQL
  • 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
  • +6

    "I might be missing something but the solution, seems to be incorrect. ... , post_pairings AS ( SELECT ps.user_id, ps.postseqid AS failpostid, ps.postseqid + 1 AS nextpostid FROM post_seq AS ps WHERE ps.issuccessfulpost IS TRUE ) -- here ps.issuccessfulpost IS TRUE the condition should be FALSE -- in that way ps.postseqid is the actual failed post(failpostid) -- Additionally, at the end the join is assumming that the sequence id is going to match the post_id, wh"

    Jaime A. - "I might be missing something but the solution, seems to be incorrect. ... , post_pairings AS ( SELECT ps.user_id, ps.postseqid AS failpostid, ps.postseqid + 1 AS nextpostid FROM post_seq AS ps WHERE ps.issuccessfulpost IS TRUE ) -- here ps.issuccessfulpost IS TRUE the condition should be FALSE -- in that way ps.postseqid is the actual failed post(failpostid) -- Additionally, at the end the join is assumming that the sequence id is going to match the post_id, wh"See full answer

    Coding
    SQL
  • 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
  • +4

    "SELECT u.userid, a.marketingchannel FROM attribution a JOIN user_sessions u ON u.sessionid = a.sessionid GROUP BY u.userid, a.marketingchannel HAVING SUM(a.purchase_value) > 100 ORDER BY MIN(u.adclicktimestamp) ASC; `"

    Derrick M. - "SELECT u.userid, a.marketingchannel FROM attribution a JOIN user_sessions u ON u.sessionid = a.sessionid GROUP BY u.userid, a.marketingchannel HAVING SUM(a.purchase_value) > 100 ORDER BY MIN(u.adclicktimestamp) ASC; `"See full answer

    Coding
    SQL
  • 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
  • +12

    "The unique id is not clear in this question"

    Anonymous Possum - "The unique id is not clear in this question"See full answer

    Coding
    SQL
  • +12

    "I'm pretty sure Exponent's answer is wrong. In the snippet below, they use "pl.name = 'Telephones' to attempt to filter down to the Telephone transactions, but they do this within a LEFT JOIN which means all product_lines rows are returned. > LEFT JOIN product_lines pl > ON p.productlineid = pl.id > AND pl.name = 'Telephones' Below is my solution. Also, I didn't see anywhere that said the "amount" column was in cents instead of dollars, but I still divided by 100 to be consistent with Exp"

    Bradley E. - "I'm pretty sure Exponent's answer is wrong. In the snippet below, they use "pl.name = 'Telephones' to attempt to filter down to the Telephone transactions, but they do this within a LEFT JOIN which means all product_lines rows are returned. > LEFT JOIN product_lines pl > ON p.productlineid = pl.id > AND pl.name = 'Telephones' Below is my solution. Also, I didn't see anywhere that said the "amount" column was in cents instead of dollars, but I still divided by 100 to be consistent with Exp"See full answer

    Coding
    SQL
  • 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
  • +6

    " with youngsuccrate as( select strftime('%m', postdate) AS postmonth, round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as yascrate from post where userid in (select userid from post_user where age between 0 and 18) group by post_month ), nonyoungsucc_rate as( select strftime('%m', postdate) AS postmonth, round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as nonyasc_rate from post where user_id in (select"

    Bhavna S. - " with youngsuccrate as( select strftime('%m', postdate) AS postmonth, round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as yascrate from post where userid in (select userid from post_user where age between 0 and 18) group by post_month ), nonyoungsucc_rate as( select strftime('%m', postdate) AS postmonth, round(sum(issuccessfulpost)*1.0/count(issuccessfulpost),2)as nonyasc_rate from post where user_id in (select"See full answer

    Coding
    SQL
  • +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
  • +5

    "productssold = set(transactions['productid']) unsoldproducts = products.loc[~products['id'].isin(productssold)] return unsold_products[["id", "name", "stock"]] `"

    Laura U. - "productssold = set(transactions['productid']) unsoldproducts = products.loc[~products['id'].isin(productssold)] return unsold_products[["id", "name", "stock"]] `"See full answer

    Coding
    Data Analysis
  • 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
Showing 41-60 of 137