Data Structures & Algorithms Interview Questions

Review this list of 65 data structures & algorithms interview questions and answers verified by hiring managers and candidates.
  • Adobe logoAsked at Adobe 
    Video answer for 'Edit distance'
    +16

    "from collections import deque def updateword(words, startword, end_word): if end_word not in words: return None # Early exit if end_word is not in the dictionary queue = deque([(start_word, 0)]) # (word, steps) visited = set([start_word]) # Keep track of visited words while queue: word, steps = queue.popleft() if word == end_word: return steps # Found the target word, return steps for i in range(len(word)): "

    叶 路. - "from collections import deque def updateword(words, startword, end_word): if end_word not in words: return None # Early exit if end_word is not in the dictionary queue = deque([(start_word, 0)]) # (word, steps) visited = set([start_word]) # Keep track of visited words while queue: word, steps = queue.popleft() if word == end_word: return steps # Found the target word, return steps for i in range(len(word)): "See full answer

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

    "Reversing a linked list is a very popular question. We have two approaches to reverse the linked list: Iterative approach and recursion approach. Iterative approach (JavaScript) function reverseLL(head){ if(head === null) return head; let prv = null; let next = null; let cur = head; while(cur){ next = cur.next; //backup cur.next = prv; prv = cur; cur = next; } head = prv; return head; } Recursion Approach (JS) function reverseLLByRecursion("

    Satyam S. - "Reversing a linked list is a very popular question. We have two approaches to reverse the linked list: Iterative approach and recursion approach. Iterative approach (JavaScript) function reverseLL(head){ if(head === null) return head; let prv = null; let next = null; let cur = head; while(cur){ next = cur.next; //backup cur.next = prv; prv = cur; cur = next; } head = prv; return head; } Recursion Approach (JS) function reverseLLByRecursion("See full answer

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

    "public static boolean isPalindrome(String str){ boolean flag = true; int len = str.length()-1; int j = len; for(int i=0;i<=len/2;i++){ if(str.charAt(i)!=str.charAt(j--)){ flag = false; break; } } return flag; }"

    Sravanthi M. - "public static boolean isPalindrome(String str){ boolean flag = true; int len = str.length()-1; int j = len; for(int i=0;i<=len/2;i++){ if(str.charAt(i)!=str.charAt(j--)){ flag = false; break; } } return flag; }"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • Video answer for 'How would you remove duplicates in a string?'
    +7

    " O(n) - characters in the string O(n) - stack def identify_adjacent(s: str, k: int) -> str: stack = [] n = len(s) for ch in s: if stack: topch, topcnt = stack[-1] if top_ch == ch: top_cnt += 1 stack[-1] = (ch, top_cnt) else: top_cnt = 1 stack.append((ch,1)) if top_cnt == k: stack.pop() else: stack.append"

    Rick E. - " O(n) - characters in the string O(n) - stack def identify_adjacent(s: str, k: int) -> str: stack = [] n = len(s) for ch in s: if stack: topch, topcnt = stack[-1] if top_ch == ch: top_cnt += 1 stack[-1] = (ch, top_cnt) else: top_cnt = 1 stack.append((ch,1)) if top_cnt == k: stack.pop() else: stack.append"See full answer

    Data Structures & Algorithms
    Coding
  • Adobe logoAsked at Adobe 
    +16

    "We can use dictionary to store cache items so that our read / write operations will be O(1). Each time we read or update an existing record, we have to ensure the item is moved to the back of the cache. This will allow us to evict the first item in the cache whenever the cache is full and we need to add new records also making our eviction O(1) Instead of normal dictionary, we will use ordered dictionary to store cache items. This will allow us to efficiently move items to back of the cache a"

    Alfred O. - "We can use dictionary to store cache items so that our read / write operations will be O(1). Each time we read or update an existing record, we have to ensure the item is moved to the back of the cache. This will allow us to evict the first item in the cache whenever the cache is full and we need to add new records also making our eviction O(1) Instead of normal dictionary, we will use ordered dictionary to store cache items. This will allow us to efficiently move items to back of the cache a"See full answer

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

  • +41

    "#include #include #include using namespace std; vector diff(const vector& A, const vector& B) { unordered_set elements; vector result; for (const auto& element : A) { elements.insert(element); } for (const auto& element : B) { if (elements.find(element) == elements.end()) { result.push_back(element); } else { elements.erase(element); } } for"

    Warrenbuff - "#include #include #include using namespace std; vector diff(const vector& A, const vector& B) { unordered_set elements; vector result; for (const auto& element : A) { elements.insert(element); } for (const auto& element : B) { if (elements.find(element) == elements.end()) { result.push_back(element); } else { elements.erase(element); } } for"See full answer

    Data Structures & Algorithms
    Coding
  • +9

    "Would be better to adjust resolution in the video player directly."

    Anonymous Prawn - "Would be better to adjust resolution in the video player directly."See full answer

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

    "we can use two pointer + set like maintain i,j and also insert jth character to set like while set size is equal to our window j-i+1 then maximize our answer and increase jth pointer till last index"

    Kishor J. - "we can use two pointer + set like maintain i,j and also insert jth character to set like while set size is equal to our window j-i+1 then maximize our answer and increase jth pointer till last index"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Explain how to find a target sum in an array.'
    +2

    "// C++ program to print the count of // subsets with sum equal to the given value X #include using namespace std; // Recursive function to return the count // of subsets with sum equal to the given value int subsetSum(int arr[], int n, int i, int sum, int count) { // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0)"

    Ajay U. - "// C++ program to print the count of // subsets with sum equal to the given value X #include using namespace std; // Recursive function to return the count // of subsets with sum equal to the given value int subsetSum(int arr[], int n, int i, int sum, int count) { // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0)"See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • Adobe logoAsked at Adobe 
    +20

    "Idea for solution: Reverse the complete char array Reverse the words separated by space. i.e. Find the space characters and the reverse the subarray between two space characters. vector reverseSubarray(vector& arr, int s, int e) { while (s reverseWords(vector& arr ) { int n = arr.size(); reverse(arr, 0, n - 1"

    Rahul M. - "Idea for solution: Reverse the complete char array Reverse the words separated by space. i.e. Find the space characters and the reverse the subarray between two space characters. vector reverseSubarray(vector& arr, int s, int e) { while (s reverseWords(vector& arr ) { int n = arr.size(); reverse(arr, 0, n - 1"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • Meta (Facebook) logoAsked at Meta (Facebook) 
    Video answer for 'Merge Intervals'
    +33

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

    "function mostCommonWords(text) { const frequencyTable = new Map(); const words = text.toLowerCase().replace(//g, '').split(' '); for (let word of words) { frequencyTable.set(word, (frequencyTable.get(word) || 0)+1); } frequencyTable.delete(''); return [...frequencyTable.entries()].sort(([w1, f1], [w2, f2]) => f2-f1 !== 0? f2-f1 : w1.charCodeAt(0)-w2.charCodeAt(0) ); } `"

    Tiago R. - "function mostCommonWords(text) { const frequencyTable = new Map(); const words = text.toLowerCase().replace(//g, '').split(' '); for (let word of words) { frequencyTable.set(word, (frequencyTable.get(word) || 0)+1); } frequencyTable.delete(''); return [...frequencyTable.entries()].sort(([w1, f1], [w2, f2]) => f2-f1 !== 0? f2-f1 : w1.charCodeAt(0)-w2.charCodeAt(0) ); } `"See full answer

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

    "this assumes that the dependency among courses is in a growing order: 0 -> 1 -> 2 -> ... if not, then the code will not work"

    Gabriele G. - "this assumes that the dependency among courses is in a growing order: 0 -> 1 -> 2 -> ... if not, then the code will not work"See full answer

    Software Engineer
    Data Structures & Algorithms
    +4 more
  • Adobe logoAsked at Adobe 
    Video answer for 'Move all zeros to the end of an array.'
    +40

    "this solution here is much faster than the exponent reference soln. It is also far more concise and easy to understand def moveZerosToEnd(arr: List[int]) -> List[int]: left = 0 for right in range(len(arr)): if arr[right] == 0: pass else: if left != right: temp = arr[left] arr[left] = arr[right] arr[right] = temp left += 1 return arr `"

    Devesh K. - "this solution here is much faster than the exponent reference soln. It is also far more concise and easy to understand def moveZerosToEnd(arr: List[int]) -> List[int]: left = 0 for right in range(len(arr)): if arr[right] == 0: pass else: if left != right: temp = arr[left] arr[left] = arr[right] arr[right] = temp left += 1 return arr `"See full answer

    Software 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
  • 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
  • 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
    Data Structures & Algorithms
    +1 more
  • Google logoAsked at Google 
    Video answer for 'Write functions to serialize and deserialize a list of strings.'
    +4

    "One thing is not clear to me, We encoded the length of the word to a character, but the max number which can be converted to char ascii is 255. How will it work for length till 65535?"

    Curly T. - "One thing is not clear to me, We encoded the length of the word to a character, but the max number which can be converted to char ascii is 255. How will it work for length till 65535?"See full answer

    Software Engineer
    Data Structures & Algorithms
    +1 more
  • +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
Showing 1-20 of 65