Coding Interview Questions

Review this list of 344 coding interview questions and answers verified by hiring managers and candidates.
  • "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
  • +19

    "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

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

    Data Scientist
    Coding
    +1 more
  • +12

    "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
  • Adobe logoAsked at Adobe 
    Video answer for 'Find the median of two sorted arrays.'
    Software Engineer
    Coding
    +4 more
  • Google logoAsked at Google 
    +2

    "WITH RECURSIVE fibonacci_series AS ( SELECT 1 AS n, 0 AS fib1, 1 AS fib2 UNION ALL SELECT n + 1 AS n, fib2 AS fib1, fib1 + fib2 AS fib2 FROM fibonacci_series WHERE n < 20 -- Limit the series to 20 numbers ) SELECT n, fib1 AS fib FROM fibonacci_series ORDER BY n; `"

    Yashasvi V. - "WITH RECURSIVE fibonacci_series AS ( SELECT 1 AS n, 0 AS fib1, 1 AS fib2 UNION ALL SELECT n + 1 AS n, fib2 AS fib1, fib1 + fib2 AS fib2 FROM fibonacci_series WHERE n < 20 -- Limit the series to 20 numbers ) SELECT n, fib1 AS fib FROM fibonacci_series ORDER BY n; `"See full answer

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

    "First of all, stack and heap memory are abstraction on top of the hardware by the compiler. The hardware is not aware of stack and heap memory. There is only a single piece of memory that a program has access to. The compiler creates the concepts of stack and heap memory to run the programs efficiently. Programs use stack memory to store local variables and a few important register values such as frame pointer and return address for program counter. This makes it easier for the compiler to gene"

    Stanley Y. - "First of all, stack and heap memory are abstraction on top of the hardware by the compiler. The hardware is not aware of stack and heap memory. There is only a single piece of memory that a program has access to. The compiler creates the concepts of stack and heap memory to run the programs efficiently. Programs use stack memory to store local variables and a few important register values such as frame pointer and return address for program counter. This makes it easier for the compiler to gene"See full answer

    Software Engineer
    Coding
    +2 more
  • "Problem: Given an input string txt consisting of alphanumeric characters and the parentheses characters '(' & ')', write a function which removes the minimum number of characters to return a version of the string with properly balanced parenthesis. Answer: You can do this with a counter. Psuedo-Python Start with counter = 0 output = [] Iterate through the string, every time you encounter a '(', increment the counter. Add the character to the output. If you encounter a ')', decrement the coun"

    Michael B. - "Problem: Given an input string txt consisting of alphanumeric characters and the parentheses characters '(' & ')', write a function which removes the minimum number of characters to return a version of the string with properly balanced parenthesis. Answer: You can do this with a counter. Psuedo-Python Start with counter = 0 output = [] Iterate through the string, every time you encounter a '(', increment the counter. Add the character to the output. If you encounter a ')', decrement the coun"See full answer

    Machine Learning 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
  • "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
  • 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
  • Adobe logoAsked at Adobe 
    Video answer for 'Move all zeros to the end of an array.'
    +39

    "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

    Software Engineer
    Coding
    +4 more
  • Amazon logoAsked at Amazon 
    +7

    "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
Showing 61-80 of 344