-
Notifications
You must be signed in to change notification settings - Fork 0
/
algo_questions.json
330 lines (330 loc) · 27.1 KB
/
algo_questions.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
[
[
[
"IsUnique",
"11 Is Unique: Implement an algorithm to determine if a string has all unique characters What if you cannot use additional data structures?"
],
[
"CheckPermutation",
"7 7, #732 12 Check Permutation: Given two strings, write a method to decide if one is a permutation of the other"
],
[
"URLify",
"pg 193 13 URLify: 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 (Note: If implementing in Java, please use a character array so that you can perform this operation in place) EXAMPLE Input: \"Mr John Smith \", 13 Output: \"Mr%20John%20Smith\""
],
[
"PalindromePermutation",
"Chapter 1 I Arrays and Strings 14 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palin\u00addrome 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 15 16 EXAMPLE Input: Tact Coa Output: True (permutations: \"taco cat\", \"atco eta\", etc)"
],
[
"OneAway",
"One Away: 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 EXAMPLE pale, ple > true pales, pale > true pale, bale > true pale, bake > false"
],
[
"StringCompression",
"String Compression: Implement a method to perform basic string compression using the counts of repeated characters For example, the string aabcccccaaa would become a2blc5a3 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 (a z)"
],
[
"RotateMatrix",
"17 Rotate Matrix: Given an image represented by an 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?"
],
[
"ZeroMatrix",
", # 100 18 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0"
],
[
"StringRotation",
"19 String Rotation:Assumeyou have a method isSubstringwhich checks ifoneword isa substring of another Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (eg, \"waterbottle\" is a rotation of\"erbottlewat\")"
]
],
[
[
"RemoveDups",
"21 Rmov Dups! Write code to remove duplicates from an unsorted linked list FOLLOW UP How would you solve this problem if a temporary buffer is not allowed?"
],
[
"ReturnKthtoLast",
"pg208 22 Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list"
],
[
"DeleteMiddleNode",
"23 Delete Middle Node: Implement an algorithm to delete a node in the middle (ie, any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node EXAMPLE lnput:the node c from the linked lista>b>c>d>e>f Result: nothing is returned, but the new linked list looks like a>b>d>e>f"
],
[
"Partition",
"\"m ''\"mm*'924 Partition: 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 If xis contained within the list, the values of x only need to be after the elements less than x (see below) The partition element x can appear anywhere in the \"right partition\"; it does not need to appear between the left and right partitions EXAMPLE Input: Output: 3 > 5 > 8 > 5 > 10 > 2 > 1 [partition= 5] 3 > 1 > 2 > 10 > 5 > 5 > 8"
],
[
"SumLists",
"Chapter 2 I Linked Lists 25 Sum Lists: 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 EXAMPLE Input: (7> 1 > 6) + (5 > 9 > 2)Thatis,617 + 295 Output: 2 > 1 > 9 That is, 912 FOLLOW UP Suppose the digits are stored in forward order Repeat the above problem EXAMPLE lnput:(6 > 1 > 7) + (2 > 9 > 5)Thatis,617 + 295 Output: 9 > 1 > 2 That is, 912"
],
[
"Palindrome",
"26 Palindrome: Implement a function to check if a linked list is a palindrome"
],
[
"Intersection",
"27 Intersection: Given two (singly) linked lists, determine if the two lists intersect Return the inter\u00adsecting node Note that 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"
],
[
"LoopDetection",
"28 Loop Detection: Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop DEFINITION Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list EXAMPLE Input: A > B > C > D > E > C [the same C as earlier] Output: C"
]
],
[
[
"ThreeinOne",
"31 Three in One: Describe how you could use a single array to implement three stacks"
],
[
"StackMin",
"32 Stack Min: 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 0(1) time"
],
[
"StackofPlates",
"Chapter 3 I Stacks and Queues 33 Stack of Plates: Imagine a (literal) stack of plates If the stack gets too high, it might topple Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold Implement a data structure SetOfStacks that mimics this SetOfStacks should be 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) FOLLOW UP Implement a function popAt ( int index) which performs a pop operation on a specific substack"
],
[
"QueueviaStacks",
"pg233 34 Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks"
],
[
"SortStack",
"74 pg 23635 Sort Stack: 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 (such as an array) The stack supports the following operations: push, pop, peek, and is Empty"
],
[
"AnimalShelter",
"# 15, #32, #43 P9 237 36 Animal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly\"first in, first out\" basis People must adopt either the \"oldest\" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type) They cannot select which specific animal they would like Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat You may use the builtin Linked list data structure"
]
],
[
[
"RouteBetweenNodes",
"41 Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes"
],
[
"MinimalTree",
"pg 241 42 Minimal Tree: Given a sorted (increasing order) array with unique integer elements, write an algo\u00adrithm to create a binary search tree with minimal height"
],
[
"ListofDepths",
"76 pg242 43 List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you'll have D linked lists)"
],
[
"CheckBalanced",
"Chapter 4 I Trees and Graphs 44 Check Balanced: 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 subtrees of any node never differ by more than one"
],
[
"ValidateBST",
"45 Validate BST: Implement a function to check if a binary tree is a binary search tree"
],
[
"Successor",
"pg 46 Successor: Write an algorithm to find the \"next\" node (ie, inorder successor) of a given node in a binary search tree You may assume that each node has a link to its parent"
],
[
"BuildOrder",
"pg 248 47 Build Order: 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 built 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 EXAMPLE Input: projects: a, b, c, d, e, f dependen cies: (a, d), (f, b), (b, d), (f, a), (d, c) Output: f, e, a, b, d, c"
],
[
"FirstCommonAncestor",
"48 First Common Ancestor: 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"
],
[
"BSTSequences",
"p9 257 49 BST Sequences: A binary search tree was created by traversing through an array from left to right and inserting each element Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree EXAMPLE Input: Output: {2, 1, 3}, {2, 3, 1}"
],
[
"OCheckSubtree",
"Chapter 4 I Trees and Graphs 41 O Check Subtree: Tl and T2 are two very large binary trees, with Tl much bigger than T2 Create an algorithm to determine if T2 is a subtree of Tl A tree T2 is a subtree of Tl if there exists a node n in Tl such that the subtree of n is identical to T2 That is, if you cut off the tree at node n, the two trees would be identical"
],
[
"RandomNode",
"265 411 Random Node: You are implementing a binary tree class from scratch which, in addition to insert, find, and delete, has a method getRandomNod e() 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"
],
[
"PathswithSum",
"412 Paths with Sum: 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 (traveling only from parent nodes to child nodes)"
]
],
[
[
"Insertion",
"51 Insertion: You are given two 32bit numbers, N and M, and two bit positions, i and jWrite a method to insert M into N such that M starts at bit j and ends at bit i Youcan assume that the bits j through i have enough space to fit all of M That is, ifM = 10011, you can assume that there are at least 5 bits between j and i You would not, forexample, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2EXAMPLE Input: N 10000000000, M Output: N = 10001001100"
],
[
"BinarytoString",
"Chapter 5 I Bit Manipulation 52 Binary to String: Given a real number between O and 1 (eg, 072) 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:'"
],
[
"FlipBittoWin",
"73, #269, #297 53 Flip Bit to Win: You have an integer and you can flip exactly one bit from a 0 to a 1 Write code to find the length of the longest sequence of ls you could create EXAMPLE Input: 1775 Output: 8 (or: 11011101111)"
],
[
"NextNumber",
"54 Next Number: Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation"
],
[
"Debugger",
"75, #242, #372, #339, #358, #375, #390 55 Debugger: Explain what the following code does: ( ( n & ( n1)) == 0)"
],
[
"Conversion",
"pg 285 56 Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B EXAMPLE Input: 29 (or: 11101), 15 (or: 01111) Output: 2"
],
[
"PairwiseSwap",
"pg286 57 Pairwise Swap: Write a program to swap odd and even bits in an integer with as few instructions as possible (eg, bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on)"
],
[
"DrawLine",
"pg 286 58 Draw Line: A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored in one byte The screen has width w, where w is divisible by 8 (that is, no byte will be split across rows) The height of the screen, of course, can be derived from the length of the array and the width Implement a function that draws a horizontal line from ( xl, y) to ( x2, y) The method signature should look something like: drawline(byte[] screen, int width, int xl, int x2, int y)"
]
],
[
[
"TheHeavyPill",
"61 The Heavy Pill: You have 20 bottles of pills 19 bottles have 10 gram pills, but one has pills of weight 11 grams Given a scale that provides an exact measurement, how would you find the heavy bottle? You can only use the scale once"
],
[
"Basketball",
"Chapter 6 I Math and Logic Puzzles 62 Basketball: You have a basketball hoop and someone says that you can play one of two games Game 1: You get one shot to make the hoop Game 2: You get three shots and you have to make two of three shots If p is the probability of making a particular shot, for which values of p should you pick one game or the other?"
],
[
"Dominos",
"P,290 63 Dominos: There is an 8x8 chessboard in which two diagonally opposite corners have been cut off You are given 31 dominos, and a single domino can cover exactly two squares Can you use the 31 dominos to cover the entire board? Prove your answer (by providing an example or showing why it's impossible)"
],
[
"AntsonaTriangle",
"64 Ants on a Triangle: There are three ants on different vertices of a triangle What is the probability of collision (between any two or all of them) if they start walking on the sides of the triangle? Assume that each ant randomly picks a direction, with either direction being equally likely to be chosen, and that they walk at the same speed Similarly, find the probability of collision with n ants on an nvertex polygon"
],
[
"JugsofWater",
"65 Jugs of Water: You have a fivequart jug, a threequart jug, and an unlimited supply of water (but no measuring cups) How would you come up with exactly four quarts of water? Note that the jugs are oddly shaped, such that filling up exactly \"half\" of the jug would be impossible"
],
[
"BlueEyedIsland",
",, 66 BlueEyed Island: A bunch of people are living on an island, when a visitor comes with a strange order: all blueeyed people must leave the island as soon as possible There will be a flight out at 8:00 pm every evening Each person can see everyone else's eye color, but they do not know their own (nor is anyone allowed to tell them) Additionally, they do not know how many people have blue eyes, although they do know that at least one person does How many days will it take the blueeyed people to leave?"
],
[
"TheApocalypse",
"()('\\ 293 67 The Apocalypse: In the new postapocalyptic world, the world queen is desperately concerned about the birth rate Therefore, she decrees that all families should ensure that they have one girl or else they face massive fines If all families abide by this policythat is, they have continue to have children until they have one girl, at which point they immediately stopwhat will the gender ratio of the new generation be? (Assume that the odds of someone having a boy or a girl on any given pregnancy is equal) Solve this out logically and then write a computer simulation of it"
],
[
"TheEggDropProblem",
"Chapter 6 I Math and Logic Puzzles 68 The Egg Drop Problem: There is a building of 100 floors If an egg drops from the Nth floor or above, it will break If it's dropped from any floor below, it will not break You're given two eggs Find N, while minimizing the number of drops for the worst case"
],
[
"Lockers",
"69 100 Lockers: There are 100 closed lockers in a hallway A man begins by opening all 100 lockers Next, he closes every second locker Then, on his third pass, he toggles every third locker (closes it if it is open or opens it if it is closed) This process continues for 100 passes, such that on each pass i, the man toggles every ith locker After his 100th pass in the hallway, in which he toggles only locker #100, how many lockers are open?"
]
],
[
[
"DeckofCards",
"71 Deck of Cards: Design the data structures for a generic deck of cards Explain how you would subclass the data structures to implement blackjack"
],
[
"CallCenter",
"72 Call Center: Imagine you have a call center with three levels of employees: respondent, manager, and director An incoming telephone call must be first allocated to a respondent who is free If the respondent can't handle the call, he or she must escalate the call to a manager If the manager is not free or not able to handle it, then the call should be escalated to a director Design the classes and data structures for this problem Implement a method dispatchCall() which assigns a call to the first available employee"
],
[
"Jukebox",
"7 3 Jukebox: Design a musical jukebox using objectoriented principles"
],
[
"ParkingLot",
"74 Parking Lot: Design a parking lot using objectoriented principles"
],
[
"OnlineBookReader",
"75 Online Book Reader: Design the data structures for an online book reader system"
],
[
"Jigsaw",
"Chapter 7 I ObjectOriented Design 76 Jigsaw: Implement an NxN jigsaw puzzle Design the data structures and explain an algorithm to solve the puzzle You can assume that you have a fitsWith method which, when passed two puzzle edges, returns true if the two edges belong together"
],
[
"ChatServer",
"# 192, #238, #283 77 Chat Server: Explain how you would design a chat server In particular, provide details about the various backend components, classes, and methods What would be the hardest problems to solve?"
],
[
"Othello",
"78 Othello: Othello is played as follows: Each Othello piece is white on one side and black on the other When a piece is surrounded by its opponents on both the left and right sides, or both the top and bottom, it is said to be captured and its color is flipped On your turn, you must capture at least one of your opponent's pieces The game ends when either user has no more valid moves The win is assigned to the person with the most pieces Implement the objectoriented design for Othello"
],
[
"CircularArray",
"79 Circular Array: Implement a CircularArray class that supports an arraylike data structure which can be efficiently rotated If possible, the class should use a generic type (also called a template), and should support iteration via the standard for (Obj o : circularArray) notation"
],
[
"Minesweeper",
"Chapter 7 I ObjectOriented Design 7 10 Minesweeper: Design and implement a textbased Minesweeper game Minesweeper is the classic singleplayer computer game where an NxN grid has B mines (or bombs) hidden across the grid The remaining cells are either blank or have a number behind them The numbers reflect the number of bombs in the surrounding eight cells The user then uncovers a cell If it is a bomb, the player loses If it is a number, the number is exposed If it is a blank cell, this cell and all adjacent blank cells (up to and including the surrounding numeric cells) are exposed The player wins when all nonbomb cells are exposed The player can also flag certain places as potential bombs This doesn't affect game play, other than to block the user from accidentally clicking a cell that is thought to have a bomb (Tip for the reader: if you're not familiar with this game, please play a few rounds on line first) This is a fully exposed board with 3 bombs This is not shown to the user The player initially sees a board with nothing exposed 1 1 1 1 *12 2 21 *11 1 1 1 1 1 1 *1 Clicking on cell (row= 1, col= O) would expose this: 2"
],
[
"FileSystem",
"The user wins when everything other than bombs has been exposed 2 2 711 File System: Explain the data structures and algorithms that you would use to design an inmemory file system Illustrate with an example in code where possible"
],
[
"HashTable",
"337 712 Hash Table: Design and implement a hash table which uses chaining (linked lists) to handle colli\u00adsions"
]
],
[
[
"TripleStep",
"81 Triple Step: 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"
],
[
"RobotinaGrid",
"Chapter 8 I Recursion and Dynamic Programming 82 Robot in a Grid: 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"
],
[
"MagicIndex",
"Prl 344 83 Magic Index: A magic index in an array A [ 0 n 1] is defined to be an index such that A[ i] = iGiven a sorted array of distinct integers, write a method to find a magic index, if one exists, inarray AFOLLOW UPWhat if the values are not distinct?"
],
[
"PowerSet",
"PQ 346 84 Power Set: Write a method to return all subsets of a set"
],
[
"RecursiveMultiply",
"348 85 Recursive Multiply: Write a recursive function to multiply two positive integers without using the *operatorYou can use addition, subtraction, and bit shifting, but you should minimize the numberof those operations"
],
[
"TowersofHanoi",
"pg350 86 Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower The puzzle starts with disks sorted in ascending order of size from top to bottom (ie, each disk sits on top of an even larger one) You have the following constraints: (1) Only one disk can be moved at a time(2) A disk is slid off the top of one tower onto another tower(3) A disk cannot be placed on top of a smaller diskWrite a program to move the disks from the first tower to the last using stacks"
],
[
"PermutationswithoutDups",
"87 Permutations without Dups: Write a method to compute all permutations of a string of unique characters"
],
[
"PermutationswithDups",
"88 Permutations with Dups: Write a method to compute all permutations of a string whose charac\u00adters are not necessarily unique The list of permutations should not have duplicates"
],
[
"Parens",
"Chapter 8 I Recursion and Dynamic Programming 89 Parens: Implement an algorithm to print all valid (eg, properly opened and closed) combinations of n pairs of parentheses EXAMPLE Input: 3 Output: ( ( () ) ) , ( () () ) , ( () ) () , () ( () ) , () () ()"
],
[
"PaintFill",
"81 O Paint Fill: Implement the \"paint fill\" function that one might see on many image editing programs That is, given a screen (represented by a twodimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color"
],
[
"Coins",
"811 Coins: Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), write code to calculate the number of ways of representing n cents"
],
[
"EightQueens",
"812 Eight Queens: Write an algorithm to print all ways of arranging eight queens on an 8x8 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"
],
[
"StackofBoxes",
"813 Stack of Boxes: You have a stack of n boxes, with widths wi, heights hi, and depths di The boxes cannot be rotated and can only be stacked on top of one another if each box in the stack is strictly larger than the box above it in width, height, and depth Implement a method to compute the height of the tallest possible stack The height of a stack is the sum of the heights of each box"
],
[
"BooleanEvaluation",
"814 Boolean Evaluation: Given a boolean expression consisting of the symbols 0 (false), 1 (true), & (AND), I (OR), and /\\ (XOR), 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 EXAMPLE countEval (\"l/\\01011\", false) > 2 countEval (\"0&0&0&1/\\ll0\", true) > 10"
]
]
]