Coding Interview Questions

Review this list of 137 interview questions and answers verified by hiring managers and candidates.
  • Meta (Facebook) logoAsked at Meta (Facebook) 
    Video answer for 'Merge Intervals'
    +34

    "const mergeIntervals = (intervals) => { const compare = (a, b) => { if(a[0] b[0]) return 1 else if(a[0] === b[0]) { return a[1] - b[1] } } let current = [] const result = [] const sorted = intervals.sort(compare) for(let i = 0; i = b[0]) current[1] = b[1] els"

    Kofi N. - "const mergeIntervals = (intervals) => { const compare = (a, b) => { if(a[0] b[0]) return 1 else if(a[0] === b[0]) { return a[1] - b[1] } } let current = [] const result = [] const sorted = intervals.sort(compare) for(let i = 0; i = b[0]) current[1] = b[1] els"See full answer

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

    "SELECT SUM(orderquantity) AS totalunitsorderedyesterday FROM orders WHERE order_date = DATE('now', '-1 DAY') `"

    Akshay D. - "SELECT SUM(orderquantity) AS totalunitsorderedyesterday FROM orders WHERE order_date = DATE('now', '-1 DAY') `"See full answer

    Coding
    SQL
  • "I used array to append. np.array does not have append and every np.vstack recreates object again. import numpy as np class Centroid: def init(self, location, vectors): self.location = location # (D,) self.vectors = vectors # (N_i, D) class KMeans: def init(self, n_features, k): self.nfeatures = nfeatures self.centroids = [ Centroid( location=np.random.randn(n_features), vectors=[] # I"

    Dinar M. - "I used array to append. np.array does not have append and every np.vstack recreates object again. import numpy as np class Centroid: def init(self, location, vectors): self.location = location # (D,) self.vectors = vectors # (N_i, D) class KMeans: def init(self, n_features, k): self.nfeatures = nfeatures self.centroids = [ Centroid( location=np.random.randn(n_features), vectors=[] # I"See full answer

    Coding
    Machine Learning
  • +11

    "--country names are UPPERCASE but the table in the in the question showing lowercase. That's why it took me a while to figure it out until I ran the country column WITH RECURSIVE Hierarchy AS ( SELECT e.Emp_ID, CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.LastName) AS FullName, e.Manager_ID, 0 AS Level, CASE WHEN e.Country = 'IRELAND' THEN s.Salary * 1.09 WHEN e.Country = 'INDIA' THEN s.Salary * 0.012 ELSE s.Salary "

    Victor N. - "--country names are UPPERCASE but the table in the in the question showing lowercase. That's why it took me a while to figure it out until I ran the country column WITH RECURSIVE Hierarchy AS ( SELECT e.Emp_ID, CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.LastName) AS FullName, e.Manager_ID, 0 AS Level, CASE WHEN e.Country = 'IRELAND' THEN s.Salary * 1.09 WHEN e.Country = 'INDIA' THEN s.Salary * 0.012 ELSE s.Salary "See full answer

    Coding
    SQL
  • +20

    "import string from collections import defaultdict def mostcommonwords(text): d = defaultdict(int) s = text.translate(str.maketrans('', '', string.punctuation)) for w in s.lower().split(): d[w] = d[w] + 1 return sorted(sorted(d.items()), reverse=True, key=lambda x: x[1]) `"

    Michael S. - "import string from collections import defaultdict def mostcommonwords(text): d = defaultdict(int) s = text.translate(str.maketrans('', '', string.punctuation)) for w in s.lower().split(): d[w] = d[w] + 1 return sorted(sorted(d.items()), reverse=True, key=lambda x: x[1]) `"See full answer

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

  • Apple logoAsked at Apple 
    +15

    "function isValid(s) { const stack = []; for (let i=0; i < s.length; i++) { const char = s.charAt(i); if (['(', '{', '['].includes(char)) { stack.push(char); } else { const top = stack.pop(); if ((char === ')' && top !== '(') || (char === '}' && top !== '{') || (char === ']' && top !== '[')) { return false; } } } return stack.length === 0"

    Tiago R. - "function isValid(s) { const stack = []; for (let i=0; i < s.length; i++) { const char = s.charAt(i); if (['(', '{', '['].includes(char)) { stack.push(char); } else { const top = stack.pop(); if ((char === ')' && top !== '(') || (char === '}' && top !== '{') || (char === ']' && top !== '[')) { return false; } } } return stack.length === 0"See full answer

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

    "Any cycle would cause the prerequisite to be greater than the course. This passes all the tests: function canFinish(_numCourses, prerequisites) { for (const [a, b] of prerequisites) { if (b > a) return false } return true } `"

    Jeremy D. - "Any cycle would cause the prerequisite to be greater than the course. This passes all the tests: function canFinish(_numCourses, prerequisites) { for (const [a, b] of prerequisites) { if (b > a) return false } return true } `"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • +13

    "The user table no longer exists as expected - I get an error that user does not contain user_id. Note that querying the table results in only user:swuoevkivrjfta select * FROM user `"

    Evan R. - "The user table no longer exists as expected - I get an error that user does not contain user_id. Note that querying the table results in only user:swuoevkivrjfta select * FROM user `"See full answer

    Coding
    SQL
  • +17

    "select name, stock from products p left join transactions t on p.id = t.product_id order by date desc limit 1"

    Daniel C. - "select name, stock from products p left join transactions t on p.id = t.product_id order by date desc limit 1"See full answer

    Coding
    SQL
  • Adobe logoAsked at Adobe 
    Video answer for 'Move all zeros to the end of an array.'
    +42

    "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

    Machine Learning Engineer
    Data Structures & Algorithms
    +4 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
  • 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
    Data Structures & Algorithms
    +1 more
  • +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
  • Adobe logoAsked at Adobe 
    +24

    " from typing import List one pass O(n) def find_duplicates(arr1: List[int], arr2: List[int]) -> List[int]: duplicates = [] i1 = i2 = 0 while i1 < len(arr1) and i2 < len(arr2): if arr1[i1] == arr2[i2]: duplicates.append(arr1[i1]) i2 += 1 i1 += 1 return duplicates debug your code below print(find_duplicates([1, 2, 3, 5, 6, 7], [3, 6, 7, 8, 20])) `"

    Rick E. - " from typing import List one pass O(n) def find_duplicates(arr1: List[int], arr2: List[int]) -> List[int]: duplicates = [] i1 = i2 = 0 while i1 < len(arr1) and i2 < len(arr2): if arr1[i1] == arr2[i2]: duplicates.append(arr1[i1]) i2 += 1 i1 += 1 return duplicates debug your code below print(find_duplicates([1, 2, 3, 5, 6, 7], [3, 6, 7, 8, 20])) `"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
    Coding
    +1 more
  • 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
    Data Structures & Algorithms
    +1 more
  • +15

    "`select employeeid, employeename, sum(maxscore) totalscore from ( select e.id employeeid, e.name employeename, tr.testid , max(tr.score) maxscore from employees e join test_results tr on e.id = tr.employee_id group by tr.employeeid, tr.testid order by 1 ) group by 1,2 order by 3 desc` `"

    Abbas M. - "`select employeeid, employeename, sum(maxscore) totalscore from ( select e.id employeeid, e.name employeename, tr.testid , max(tr.score) maxscore from employees e join test_results tr on e.id = tr.employee_id group by tr.employeeid, tr.testid order by 1 ) group by 1,2 order by 3 desc` `"See full answer

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

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

    "-- 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 21-40 of 137