Coding Interview Questions

Review this list of 363 coding interview questions and answers verified by hiring managers and candidates.
  • Amazon logoAsked at Amazon 
    +8

    "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
    Coding
    +1 more
  • "It's a 2Sum question with duplicate array elements."

    Anzhe M. - "It's a 2Sum question with duplicate array elements."See full answer

    Data Engineer
    Coding
    +1 more
  • Adobe logoAsked at Adobe 
    +24

    "In python def find_duplicates(arr1: List[int], arr2: List[int]) -> List[int]: result = list(set(arr1) & set(arr2)) return result "

    Sammy R. - "In python def find_duplicates(arr1: List[int], arr2: List[int]) -> List[int]: result = list(set(arr1) & set(arr2)) return result "See full answer

    Data Engineer
    Coding
    +2 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
    Coding
    +3 more
  • Google logoAsked at Google 

    "def encode(root): if not root: return [] def dfs(node): if not node: return res.append(node.val) res.append(len(node,children)) for child_node in node.children: dfs(child_node) res = [] dfs(root) return res def decode(arr): if not arr: return None n = len(arr) i = 0 def dfs(val, children_count): if children_count == 0: return Node(val) cur_node = Node(val) cur_node.children = [] for j in range(children_count): nonlocal i i += 2 cur_node.children.append(dfs(arr[i], arr[i"

    Ying T. - "def encode(root): if not root: return [] def dfs(node): if not node: return res.append(node.val) res.append(len(node,children)) for child_node in node.children: dfs(child_node) res = [] dfs(root) return res def decode(arr): if not arr: return None n = len(arr) i = 0 def dfs(val, children_count): if children_count == 0: return Node(val) cur_node = Node(val) cur_node.children = [] for j in range(children_count): nonlocal i i += 2 cur_node.children.append(dfs(arr[i], arr[i"See full answer

    Software Engineer
    Coding
  • 🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.

  • +7

    "In the question it says: "above the overall average total posts", which to me implying a >, yet in the solution it uses >= Caused me 1 hr to find out. plz fix"

    Peter W. - "In the question it says: "above the overall average total posts", which to me implying a >, yet in the solution it uses >= Caused me 1 hr to find out. plz fix"See full answer

    Coding
    SQL
  • "def changeString(org: str,target:str) -> bool: lOrg = len(org) lTarget = len(target) \# They have to be equal in lenght if lOrg != lTarget: return False counter1 = Counter(org) counter2 = Counter(target) \# Counter internally iterates through the input sequence, counts the number of times a given object occurs, and stores objects as keys and the counts as values. if counter1 != counter2: return False diff = sum(org[i] != target[i] for i in range(n)) return diff == 2 or (diff == 0 and any(v > 1 f"

    Rafał P. - "def changeString(org: str,target:str) -> bool: lOrg = len(org) lTarget = len(target) \# They have to be equal in lenght if lOrg != lTarget: return False counter1 = Counter(org) counter2 = Counter(target) \# Counter internally iterates through the input sequence, counts the number of times a given object occurs, and stores objects as keys and the counts as values. if counter1 != counter2: return False diff = sum(org[i] != target[i] for i in range(n)) return diff == 2 or (diff == 0 and any(v > 1 f"See full answer

    Coding
    Data Structures & Algorithms
  • 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
    Coding
    +1 more
  • +1

    "Approach 1: Use sorting and return the kth largest element from the sorted list. Time complexity: O(nlogn) Approach 2: Use max heap and then select the kth largest element. time complexity: O(n+logn) Approach 3: Quickselect. Time complexity O(n) I explained my interviewer the 3 approaches. He told me to solve in a naive manner. Used Approach 1 had some time left so coded approach 3 also The average time complexity of Quickselect is O(n), making it very efficient for its purpose. However, in"

    GalacticInterviewer - "Approach 1: Use sorting and return the kth largest element from the sorted list. Time complexity: O(nlogn) Approach 2: Use max heap and then select the kth largest element. time complexity: O(n+logn) Approach 3: Quickselect. Time complexity O(n) I explained my interviewer the 3 approaches. He told me to solve in a naive manner. Used Approach 1 had some time left so coded approach 3 also The average time complexity of Quickselect is O(n), making it very efficient for its purpose. However, in"See full answer

    Software Engineer
    Coding
    +1 more
  • Amazon logoAsked at Amazon 

    "1) select avg(session) from table where session> 180 2) select round(sessiontime/300)*300 as sessionbin, count() as sessioncount from table group by round(sessiontime/300)300 order by session_bin 3) SELECT t1.country AS country_a, t2.country AS country_b FROM ( SELECT country, COUNT(*) AS session_count FROM yourtablename GROUP BY country ) AS t1 JOIN ( SELECT country, COUNT(*) AS session_count FROM yourtablename `GROUP BY countr"

    Erjan G. - "1) select avg(session) from table where session> 180 2) select round(sessiontime/300)*300 as sessionbin, count() as sessioncount from table group by round(sessiontime/300)300 order by session_bin 3) SELECT t1.country AS country_a, t2.country AS country_b FROM ( SELECT country, COUNT(*) AS session_count FROM yourtablename GROUP BY country ) AS t1 JOIN ( SELECT country, COUNT(*) AS session_count FROM yourtablename `GROUP BY countr"See full answer

    Data Analyst
    Coding
    +2 more
  • Amazon logoAsked at Amazon 
    Video answer for 'Implement k-means clustering.'

    "i dont know"

    Dinesh K. - "i dont know"See full answer

    Machine Learning Engineer
    Coding
    +5 more
  • "naive solution: def countprefixpairs(words): n = len(words) count = 0 for i in range(n): for j in range(i + 1, n): if words[i].startswith(words[j]) or words[j].startswith(words[i]): count += 1 return count using tries for when the list of words is very long: from collections import Counter class TrieNode: def init(self): self.children = {} self.count = 0 # To count the number of words ending at this node"

    Anonymous Unicorn - "naive solution: def countprefixpairs(words): n = len(words) count = 0 for i in range(n): for j in range(i + 1, n): if words[i].startswith(words[j]) or words[j].startswith(words[i]): count += 1 return count using tries for when the list of words is very long: from collections import Counter class TrieNode: def init(self): self.children = {} self.count = 0 # To count the number of words ending at this node"See full answer

    Software Engineer
    Coding
  • Google logoAsked at Google 
    +18

    "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

    Software Engineer
    Coding
    +1 more
  • Amazon logoAsked at Amazon 

    "input_logs = [ f"{senderid} {receiverid} {transaction_count}" "1 2 2", "3 2 42", "2 2 22", "1 1 12", "2 1 1", "2 5 4", "4 2 15" ] input_threshold = 20 exptected_output = [ list of user_ids that made more than 20 transactions sorted by number of transactions in descending order "3", # 42 transactions "2", # 27 transactions (22 + 1 + 4) #"4", # 15 transactions #"1" # 14 transactions (2 + 12 + 1) ] def gettopapi_users(logs, thres"

    Anonymous Unicorn - "input_logs = [ f"{senderid} {receiverid} {transaction_count}" "1 2 2", "3 2 42", "2 2 22", "1 1 12", "2 1 1", "2 5 4", "4 2 15" ] input_threshold = 20 exptected_output = [ list of user_ids that made more than 20 transactions sorted by number of transactions in descending order "3", # 42 transactions "2", # 27 transactions (22 + 1 + 4) #"4", # 15 transactions #"1" # 14 transactions (2 + 12 + 1) ] def gettopapi_users(logs, thres"See full answer

    Software Engineer
    Coding
    +1 more
  • +8

    "def lowestearningemployees(employees: pd.DataFrame) -> pd.DataFrame: selectedcolumns = employees[['id','firstname','last_name','salary' ]] sorteddf = selectedcolumns.sort_values(by='salary', ascending=True) return sorted_df.head(3)"

    Shatabdi P. - "def lowestearningemployees(employees: pd.DataFrame) -> pd.DataFrame: selectedcolumns = employees[['id','firstname','last_name','salary' ]] sorteddf = selectedcolumns.sort_values(by='salary', ascending=True) return sorted_df.head(3)"See full answer

    Coding
    Data Analysis
  • +16

    "WITH max_score AS ( SELECT test_id, employee_id, MAX(score) AS best_score FROM test_results GROUP BY testid, employeeid ) SELECT ms.employee_id, e.name, SUM(bestscore) AS totalscore FROM max_score as ms JOIN employees as e ON ms.employee_id = e.id GROUP BY ms.employee_id ORDER BY totalscore DESC, ms.employeeid `"

    Salome L. - "WITH max_score AS ( SELECT test_id, employee_id, MAX(score) AS best_score FROM test_results GROUP BY testid, employeeid ) SELECT ms.employee_id, e.name, SUM(bestscore) AS totalscore FROM max_score as ms JOIN employees as e ON ms.employee_id = e.id GROUP BY ms.employee_id ORDER BY totalscore DESC, ms.employeeid `"See full answer

    Coding
    SQL
  • Adobe logoAsked at Adobe 
    Video answer for 'Product of Array Except Self'
    +41

    "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
    Coding
    +3 more
  • TikTok logoAsked at TikTok 
    Video answer for 'Split an array into equal sum subarrays'
    Data Engineer
    Coding
    +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
    Coding
    +1 more
  • +19

    "-- Write your query here select p.id, p.title, p.budget, count(e.id) as num_employees, sum(e.salary) as total_salaries from projects p join employeesprojects ep on p.id = ep.projectid join employees e on ep.employee_id = e.id group by 1 order by 5 desc; `"

    Anonymous Roadrunner - "-- Write your query here select p.id, p.title, p.budget, count(e.id) as num_employees, sum(e.salary) as total_salaries from projects p join employeesprojects ep on p.id = ep.projectid join employees e on ep.employee_id = e.id group by 1 order by 5 desc; `"See full answer

    Coding
    SQL
Showing 81-100 of 363