Cracking the Coding Interview

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

You are given two 32-but numbers N and M, and two bit positions i and j. Write a method to insert M into N such that M starts at but j and ends at but i. You can assume that the bits j through i have enough space to fit all of M.

1. Clear the bits j through i by creating a left and right mask. LeftMask = ~0 << (j + 1) RightMask = (1 << i) - 1 CompleteMask = leftMask | rightMask 2. Clear out bits j through i in N: N & completeMask 3. Shift M over i bits 4. Return N | shiftedM

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

1. Create an array of 128 characters 2. Iterate through every character and check if arr[char at i] is True 3. If it is, return False 4. If it's not, set it to be True If you can't use extra space, you can sort and then iterate and see if the next char is every equal to the current char.

Write a method to compute all permutations of a string of unique characters.

1. For each character in the string, find all permutations of the string not including the character. 2. For each permutation, add a permutation that appends the character to the beginning. 3. Base cases: If string size is one: Return string If string size is zero: Return ""

Given two strings, write a method to decide if one is a permutation of the other.

1. Go through each char in each string and create a running count of the occurrences of each char 2. Go through the map and make sure the counts for each char are the same. Return False if you find a difference in char numbers 3. Return True otherwise

Implement a function to check if a linked list is a palindrome

1. Have a fast runner and a slow runner and put the slow runner's values on to a stack 2. When the fast runner reaches null, the slow runner should be in the middle 3. Keep going through the slow runner and compare it's value to the top of the stack 4. If you notice a value that's different return False 5. Otherwise, return True

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

1. Iterate through both lists 2. Keep track of an excess variable 3. Check that both lists are not null 4. Add their digits and excess to get digitSum 5. If digitSum >= 10, excess is 1 otherwise it's 0 6. Add digitSum % 10 to the list 7. Finally, if excess is not 0, add excess to the list.

Given two singly linked lists, determine if the two lists intersect. Return the intersection node. Note the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting.

1. Iterate through both lists and keep track of their lengths 2. If they don't share the same tail, return NULL because that means there's no intersection 3. Take the difference of the lengths and start the longer list into that difference 4. Iterate through both lists until you find an intersecting node and return that node

Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string.

1. Iterate through string and figure out how many spaces there are. 2. Index = trueLength + spaceCount*2 3. Iterate backwards from trueLength - 1 to 0. This represents going backwards in the actual string 4. If str[i] == ' ', then: str[index - 1] = '0' str[index - 2] = '2' str[index - 3] = '%' Index = index - 3 since we just added 3 characters 5. Else if char at i is not a space: str[index-1] = str[i] Index- -

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the compressed string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters.

1. Keep a consecutiveCounter and initialize it to 0. Keep a resultString and initialize it to "". 2. Iterate through string and increment consecutiveCounter 3. If your at the last char or if the current char is not equal to the next char: ResultString += char + consecutiveCounter consecutiveCounter = 0 4. Only return resultString if it's length is less than the original string. Otherwise, return the original string.

Create the data structure to maintain the system for an animal shelter

1. Keep a separate linked list for dogs and cats and put a time stamp to figure out which should be dequeued first

Write an algorithm such that if an element in an MxN matrix is 0, it's entire row and column are set to 0.

1. Keep one list of rows and one list of columns 2. Iterate through matrix and if you find a 0, add the row to the row list and the col to the column list 3. Go through each row in the row list and zero it out 4. Go through each column in the column list and 0 it out

Implement an algorithm to print all valid (i.e. properly opened and closed) combinations of n pairs of parenthesis.

1. Keep track of what index you're on 2. At each index, you can choose to place either a "(" or a ")". 3. You can put a "(" as long as there are left parenthesis remaining 4. You can put a ")" only if there's less right parenthesis in the string than left parenthesis 5. Recurse with updates string, updated index, and updated counts for numbers of left and right parenthesis remaining.

Implement an algorithm to find the kth to last element of a singly linked list

1. Keep two pointers p1 and p2 2. Move p1 K nodes in 3. Start p2 at the beginning and move both one node at a time until p1 is at the end

Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure. The stack supports the following operations: push, pop, peek, isEmpty

1. Look at the top thing on the original stack 2. Keep moving things onto the original stack until you find the place to put the Val 3. Keep doing this until original stack is empty

Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node

1. N.data = n.next.data 2. N.next = n.next.next

Write a method to return all subsets of a set

1. Pick an element from the set 2. Call allSubsets on the remaining part of the set 3. For every subset returned create a copy of that set including the element that was taken out. Base cases: If set size is empty, return empty

In array of integers, a 'peak' is an element which is greater than or equal to the adjacent integers and a 'valley' is an element which is less than or equal to the adjacent integers. For example, in the array {5, 8, 6, 2, 3, 4, 6}, {8, 6} are peaks and {5, 2} are valleys. Given an array of integers, sort the array into an alternating sequence of peaks and valleys.

1. Sort the array 2. Divide array into two halves 3. Inset from array1, then insert from array2 until all elements are used up

Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color.

1. Start at the point 2. If it's already the new color, then return because there's nothing to be changed 3. If it's not the new color, then change it to the new color and recurse on it's horizontal and vertical neighbors

A magic index in an A[1...n-1] is defined to be an index such that A[i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.

1. Start with middle element, mid 2. If nothing found, recurse on left side and right side 3. LeftSide = min(midIndex - 1, midValue) 4. RightSide = min(midIndex + 1, midValue)

Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.

1. To be a palindrome a word needs to have at most one character with an odd count 2. Go through each string and keep track of the character counts in a map 3. Make sure that at most one char has an odd count 4. Return True if that's the case and False otherwise

Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth.

1.Create a hash table that maps level to linkedList. 2. Pass level + 1 to children in recursive calls 3. Add current node to hasmap[level]

There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.

A replacement just means that the strings are different in only one place. An insertion and deletion just mean that if you compared the strings, they would be identical, except for a shift in one place. 1. If the string1 == string2, return True 2. If len(string1) == len(string2), check that the strings have a replacement by going through each index and making sure that they differ at most one index 3. If len(string1) == len(string2) + 1 or len(string1) + 1 == len(string2), then do checkShift(shorter, longer) 4. checkShift(shorter, longer): Index1 = 0 Index2 = 0 While ( index1 < len(shorter) and index2 < len(longer)) { 1. If the chars are different: If index1 != index2 then return False Index2++ Else: Index1++ Index2++ } Return True

You are given a list of projects and a list of dependencies (which is a list of pairs of projects where the second project is dependent on the first project). All of a project's dependencies must be valid before the project is. Find a build order that will allow the projects to be built. If there is no valid build order, return an error.

Add edges to graph such that a points to b if b is dependent on a. 1. Go through graph and add everything with no dependencies to the build order. 2. Have a pointer that points to node being processed and start it at the beginning of the array. 3. Process each node by going through all of it's children and decrementing their dependency counts by 1. If you find that a child now has 0 dependencies, add it to the build order. 4. Move the processed pointer + 1 5. If processed pointer is at the end but not all nodes were added to the build order, then no build order is possible 6. If all nodes have been processed, then build order is found

Given a Boolean expression consisting of 0(False), 1(True), &, |, and ^, and a desired Boolean result value 'result', implement a function to count the number of ways of parenthesizing the expression such that it evaluates to result. The expression should be fully parenthesized but not extraneously.

Consider putting a parenthesis after every element, and evaluate the left and right sides. Def countEval(s, Boolean result): If s == '': Return 0 If len(s) == 1: Return s Ways = 0 For i I'm xrange(len(s), +2): C = s[i] Left = s[0: i] Right = s[i + 1:] LeftTrue = countEval(left, True) RightTrue = countEval(right, True) LeftFalse = countEval(left, False) RightFalse = countEval(right, False) Total = (leftTrue + leftFalse) * (rightTrue + rightFalse) TotalTrue = 0 If c == ^: TotalTrue = leftTrue*rightFalse + leftFalse*rightTrue Elif c == &: TotalTrue = leftTrue*rightTrue Else: TotalTrue = leftTrue*rightFalse + leftFalse*rightTrue + leftTrue*rightTrue SubProblemWays = result ? TotalTrue: total -TotalTrue Ways += subProblemWays Return ways

You have an array with all numbers from 1 to N, where N is at most 32,000. The array may have duplicate entries and you do not know what N is. With only 4 kilobytes of memory available, how would you print all duplicate elements in the array.

Create a bit vector of 32,000. Go through the array and set bit[elem] on when you see elem. if the bit is already on, you know it's a duplicate so you can print it.

Implement a function to check if a binary tree is a binary search tree.

Def checkBST(Root, min, max): If root == None: Return True If ( (min != None && n.data <= min) || (max != None && n.data > max)): Return False If ( !checkBST(n.left, min, n.data) || !checkBST(n.right, n.data, max)): Return False Return True

Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two sub trees of any node never differ by more than one.

Def checkHeight(root): If root == None: Return -1 LeftHeight = checkHeight(root.left) If (leftHeight == integer.min_val): return int.min RightHeight = checkHeight(root.right) If (rightHeight == integer.min_val): return int.min HeightDiff = leftHeight - rightHeight If (math.abs(heightDiff) > 1): Return int.min_val Else: Return math.max(leftHeight, rightHeight) + 1

You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards.

Def printKPath(root, path): If root == None: Return Path.append(root.val) printKPath(root.left, path) printKPath(root.right, path) #check if path has any parts summing to k Sum = 0 For i in range(len(path)-1, -1, -1): Sum += path[i] If sum == k: PrintPath(path, i) path.pop(-1) #remove the last element from path

Describe how you could use a single array to implement three stacks.

Divide the array into three parts and add accordingly. If you wanted to have it be expandable, then when a stack exceeds it size, expand the array and move over all the elements accordingly

Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally in sorted order.

Do a modified form of binary search: Example: [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14] Let's say we're looking for 19. 1. We check if the right most element is greater than mid. If it is, then the right half is ordered. If 19 falls in the range of [mid, right], we recurse on the right side. 2. If 19 doesn't fall in [mid, right], then we know that it must be in the left half of the array, so we recurse on the left half.

Given M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element.

Do binary search on rows to figure out which row to look at. Then do binary search on columns.

Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.

Do binary search, except for the one exception that if mid is an empty string, move left and right until you find a non empty string, and then recurse on either side depending on whether or not the word of interest is less than or greater than the mid word.

Given an image represented by and NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

For (int layer = 0; layer < n/2 ; layer++ ) { Int first = layer Int last = n - 1 - layer For (int i = first; i < last; i++) { Int offset = i - first Int top = matrix[first][i] matrix[first][i] = matrix[last - offset][first] matrix[last-offset][first] = matrix[last][last-offset] matrix[last][last-offset] = matrix[i][last] matrix[i][last] = top } }

You are implementing a binary search tree class from scratch, which, in addition to insert, find, and delete, has a method getRandomNode() which returns a random node from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm for getRandomNode, and explain how you would implement the rest of the methods.

Generate a random index and then use binary search to find the node at the index. Have every node keep track of how many children it has. That way if your index is 5 and the left subtree has 3 nodes, then you need to recurse on the right subtree but you need to set index to be index - leftsize - 1

You have an integer and you can flip exactly one bit from 0 to a 1. Write code to find the length of the longest sequence of 1s you could create.

Go through the bits and compress it in a list so that you have a list of numbers where the first number is how many 0s in the first sequence of 0s and the second number is how many 1s in the first sequence of 1s and so on. 1. Look at each sequence of 0s 2. Look to the left and right, if the sequence of 0s is of size 1, you can combine the left and right sequences of 1s 3. If the sequence of 0s is greater than 1, you can add one bit to either the left or the right sequences of 1s. 4. If the sequence of 0s is 0, then you can take either the left or right side depending on which is bigger (this solves the edge case of having a bit array that's all 1s or all 1s and then some 0s)

Implement a data structure SetOfStacks that is composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop() should return the same values as it would if there were just a single stack).

Have a list and when one stack reaches capacity, add a new stack

Write an algorithm to find the 'next' node (I.e. in order successor) of a given node in a binary search tree. You may assume that each node has a link to its parents.

If the node has a right subtree, then just return the left most node in the right subtree. If the node has no right subtree, then go up the tree and find the first right ancestor. Meaning, you keep going up the parents until you find a node that is a left child and you return its parents.

Write code to remove duplicates from an unsorted linked list

If you can have extra space: 1. Iterate through linked list and and use a set to keep track of things you've seen 2. If you've already seen something, set the prev to be n.next 3. If you haven't seen something, then add it to the set and keep moving forward If you CANNOT have extra space: 1. Iterate through the list and for each iteration have a runner pointer look for duplicates and remove them. This takes more time but uses less space

Write a recursive function to multiply two positive integers without using the * operator (or / operator). You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations.

If you have 31 x 35, this means your adding 35 over and over again 31 times. Therefore, you need a way to split the problem and recurse on the children. 1. If the number is even, divide the number in 2 and recurse on both halves 2. If the number is odd, do secondHalf = n - n/2 3. Add the products that you get back 4. Base cases: if the smaller number is 0, return 0 5. If the smaller number is equal to 1, return the bigger number 6. If smaller in cache, then return cache[smaller]

Explain what the following code does: (( n & (n-1)) == 0

If you subtract 1 from n, then what you're modifying the least significant bit in the following manner: If it's a 1, you change it to a 0. If it's a 0, you make every trailing a 1 and make the point it trailed up to a 0. If you AND n and n -1 and get 0, then that means that they have no 1s in common. This will only happen if n is a power of 2.

Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. The partition element x can appear anywhere in the "right partition" it does not need to appear between left and right partitions.

Iterate through list and add nodes that are less than partition value to the beginning of the list

Write a function to determine the number of bits you would need to flip to convert integer A to integer B.

Just count the number of 1's in A ^ B. This works, because the ^ operation will give you a 1 when A and B differ in bit values at a location.

Imagine you are reading in a stream of integers. Periodically, you wish to be able to look up the rank of a number x (the number of values less than or equal to x). Implement the data structures and algorithms to support these operations.

Keep a binary search tree, but have every node keep track of how many nodes are in it's left subtree. Then, when you're searching for the element, you add the counters along your path. You need to keep track of how many nodes in left tree because as you progress in ranking, you're skipping all the elements in the left subtree.

How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.

Keep a second stack that keeps track of mins: 1. If a new value is added that is less than it equal to the current min, push it on to the minStack 2. If you pop a value equal to min, pop it off the stack too

Implement a MyQueue class which implements a queue using two stacks.

Keep one stack for the oldest items and one stack for the newest items: 1. When you add an item to the queue, push it onto the newStack 2. When you dequeue an item, pop it off of the old stack. If the old stack is empty, move everything in the new stack onto the old stack and then pop

Given a real number between 0 and 1 that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print ERROR.

Let's say the number is 0.834 Hypothetically, let's say the binary representation of that is 0.010101 Then, you can figure out the binary representation from the decimal representation by repeatedly multiplying by 2. This will shift the bits left and tell you if the next bit should be a 1 or a 0.

Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off-limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

Look at the spot to the top and look at the spot to the left. If neither are blocked, then find a path to them and add the current node to the path.

Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.

Make the root the middle element and then pass the left subarray and right subarray to be the left and right child: Def createMinimalBST(arr, start, end): If end < start: Return none Mid = (start + end)/2 N = treeNode(arr[mid]) N.left = createMinBST(arr, start, mid -1) N.right = createMinBST(arr, mid+1, end) Return N

Write a method to sort an array of strings so that all the anagrams are grouped together.

Sort the array, but have the comparison function check if two strings are anagrams instead of comparing alphabetically. To check that two strings are anagrams, just check if they're equal when they're sorted.

Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.

Start at root and check if pIsOnLeft and qIsOnLeft using the cover function. If pIsOnLeft != qIsOnLeft, then you can return root. Otherwise, recurse on left child if pIsOnLeft and recurse on right child if !pIsOnLeft. Def covers(root, p): If root == None: return False If root == p: return True Return covers(root.left, p) || covers(root.right, p).

You are given two sorted arrays A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.

Start at the end of the array, if A is greater, put A's value. If B is greater, put B's value. Do this until you've exhausted all elements of A and B.

Write a program to swap odd and even bits in an integer with as few instructions as possible.

The key here is that the hex value 0xAA is really 101010 and the hex value 0x55 is really 01010101. Therefore, we can extract the odd bits using AA and extract the even bits using 55. Return (x & AA) >>> 1 | (x & 55) << 1

T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree of T1.

Two trees will be identical if their pre-order traversals are identical. Therefore, you can look at the pre-order traversals of both as strings and check if T2's string is a substring of T1's string.

Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

Use BFS starting from the start node. Return true if one of the nodes you visit along the way is the end node. Otherwise, return False.

You are given an array-like data structure Listy which lacks a size method. It does, however, have an elementAt(i) method that returns the element at index i in O(1) time. If i is beyond the bounds of the data structure, it returns -1. Given a Listy which contains sorted, positive integers, find the index at which an element x occurs. If x occurs multiple times, you may return any index.

Use powers of two to get a rough estimate of the length of the array. 1. Check elementAt(2), checkElementAt(4), checkElementAt(8), etc... until you get a -1. 2. Now do binary search, except if you find -1, make sure to always recurse on the left array.

Write an algorithm to print all ways of arranging eight queens on an 8 x 8 chess board so that none of them share the same row, column, or diagonal. In this case, 'diagonal' means all diagonals, not just the two that bisect the board.

We can approach this problem row by row. We want to know how many combinations there are if we place the first queen at row 0, on col 0, 1, 2, 3, ...etc Def placeQueens (row, columns, results): If row == Len(grid): Results.add(columns.clone) Else: For col in xrange(len(grid[0])): If checkValid(columns, row, col): Columns[row] = col PlaceQueens(row + 1, columns, results)

Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (e.g. water bottle is a rotation of erbottlewat)

We know that waterbottle is XY and erbottlewat is YX. We also know that YX will always be a substring of XYXY. Therefore, s2 is a rotation of s1 if and only if s2 is a substring of s1s1.

Imagine you have a 20 GB file with one string per line. Explain how you would sort this file.

You would take load only chunks of the memory at a time, sort each chunk, and then combine chunks.

Given an input file with four billion non-negative integers, provide an algorithm to generate an integer that is not contained in the file. Assume you have 1GB of memory available for this task.

You would use the 1GB to come up with a bit vector. Go through all elements and flip but i to on if you find element i. If you go through and find an element with an off but vector, then you can say that i is not in the file.

A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.

def countWays: if (n < 0): Return 0 Elif n == 0: Return 1 Elif memo[n] > -1: Return memo[n] Else: Memo[n] = countWays(n-1, memo) + countWays(n-2, memo) + countWays(n-3, memo) Return memo[n]


Kaugnay na mga set ng pag-aaral

UNIT 3: PHOTOSYNTHESIS AND THE PLANT BODY

View Set

CH 13Marketers: Helping Buyers Buy

View Set

A&P Urinary and Male/Female reproductive systems

View Set

Azure 900 Study Cards - Describe Azure Architecture and Services

View Set