Skip to content

Instantly share code, notes, and snippets.

@thmsdnnr
Created June 13, 2019 06:14
Show Gist options
  • Save thmsdnnr/5d065cdba8ed5794b5f2bd166e07f62c to your computer and use it in GitHub Desktop.
Save thmsdnnr/5d065cdba8ed5794b5f2bd166e07f62c to your computer and use it in GitHub Desktop.
{"title":"Ultimate CS Deck","cards":[{"title":"card_1","front":"What is Hamming Code?","back":"In telecommunication, Hamming codes are a family of linear error-correcting codes that generalize the Hamming(7,4)-code, and were invented by Richard Hamming in 1950. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors.\n"},{"title":"card_2","front":"What is the square root of 256?","back":"16\n"},{"title":"card_3","front":"2^16","back":"65,536\n"},{"title":"card_4","front":"Using bitwise operations, how would you test that a number is a power of 2?","back":"bool isPowerOfTwo = (x & (x - 1);\n"},{"title":"card_5","front":"What does ELF stand for?","back":"Executable and Linkable Format.\nIt's a common standard file format for executables, object code, shared libraries, and core dumps.\n"},{"title":"card_6","front":"example of a latency device","back":"CPU core\n"},{"title":"card_7","front":"example of a throughput device","back":"GPU core\n"},{"title":"card_8","front":"What is the Hamming Distance?","back":"A number used to denote the number of differences between two binary strings of the same length.\n"},{"title":"card_9","front":"What are the 5 steps of the compiling process?","back":"Lexical Analysis\nParsing\nSemantic Analysis\nOptimization\nCode Generation\n"},{"title":"card_10","front":"What is parsing?","back":"Combining tokens and groups of tokens into a tree structure (a parse tree).\n"},{"title":"card_11","front":"What is lexical analysis?","back":"The process of dividing program text into words or tokens.\n"},{"title":"card_12","front":"What is code generation?","back":"Producing a translation from a high-level program to assembly code. (Linker and Archiver taker over from here to produce machine code)\n"},{"title":"card_13","front":"4 * 16","back":"64\n"},{"title":"card_14","front":"2 ^ 4","back":"16\n"},{"title":"card_15","front":"2^3","back":"8\n"},{"title":"card_16","front":"2^5","back":"32\n"},{"title":"card_17","front":"2^6","back":"64\n"},{"title":"card_18","front":"2^7","back":"128\n"},{"title":"card_19","front":"2^8","back":"256\n"},{"title":"card_20","front":"2^9","back":"512\n"},{"title":"card_21","front":"2^10","back":"1024\n"},{"title":"card_22","front":"2^11","back":"2048\n"},{"title":"card_23","front":"2^12","back":"4096\n"},{"title":"card_24","front":"2^13","back":"8192\n"},{"title":"card_25","front":"2^14","back":"16,384\n"},{"title":"card_26","front":"2^15","back":"32,768\n"},{"title":"card_27","front":"2^32","back":"4.294 Billion\n"},{"title":"card_28","front":"size of char in bits","back":"8 bits\n"},{"title":"card_29","front":"size of char in bytes","back":"1 byte\n"},{"title":"card_30","front":"size of bool in bits","back":"8 bits\n"},{"title":"card_31","front":"size of short in bits","back":"16 bits (at least), and 16 commonly\n"},{"title":"card_32","front":"size of short in bytes","back":"2 bytes, and 2 bytes commonly\n"},{"title":"card_33","front":"size of int in bits","back":"32 bits commonly, at least 16 bits\n"},{"title":"card_34","front":"size of int in bytes","back":"4 bytes commonly, at least 2 bytes\n"},{"title":"card_35","front":"size of long in bits","back":"32 (at least, 32 commonly), 64 on LP64\n"},{"title":"card_36","front":"size of long in bytes","back":"4 bytes, (at least 4, and commonly 4), 8 on LP64\n"},{"title":"card_37","front":"size of long long in bits","back":"64 bits\n"},{"title":"card_38","front":"size of long long in bytes","back":"8 bytes\n"},{"title":"card_39","front":"size of float in bits","back":"32 bits\n"},{"title":"card_40","front":"size of float in bytes","back":"4 bytes\n"},{"title":"card_41","front":"size of double in bits","back":"64 bits\n"},{"title":"card_42","front":"size of double in bytes","back":"8 bytes\n"},{"title":"card_43","front":"size of wchar_t in bits","back":"16 bits\n"},{"title":"card_44","front":"size of wchar_t in bytes","back":"2 bytes\n"},{"title":"card_45","front":"How many levels in a complete binary tree of size n?","back":"floor(1 + log(base2)(n))\n"},{"title":"card_46","front":"How can build heap be done in linear time?","back":"A tree of size n nodes, will have floor(n/2^h) nodes with height >= h.\nThe last half of nodes will be leaves, so they already satisfy the heap property. No work needs to be done on them.\ngoing bottom-up (ignoring the last n/2 items) and satisfying the heap property one level at a time, each level going up the tree has to do at most 1 operation more than the level below it. But as you go up the tree, higher levels have fewer nodes, so you may be doing more operations, but it happens on fewer number of times.\nThis resembles a series:\n\nn/2 - height 1: 1 operations\nn/4 - height 2: 2 operation\nn/8 - height 3: 3 operations\n...\ngoing to floor(n/2^h) - height h: h operations\n\nn * (1/2 + 2/4 + 3/8 + 4/16 ....) = n * 1 = n\n"},{"title":"card_47","front":"How are queues usually implemented?","back":"Using a Circular Array or Singly Linked List.\n"},{"title":"card_48","front":"How is a deque usually implemented?","back":"Using a Circular Array or Doubly Linked List.\n"},{"title":"card_49","front":"How would you swap 2 integers using only bitwise operations?","back":"a ^= b\nb ^= a\na ^= b\n"},{"title":"card_50","front":"How would you turn ON the 3rd bit from the end in a bitstring?","back":"x |= (1 << 2)\n"},{"title":"card_51","front":"How would you turn OFF the 3rd bit from the end in a bitstring?","back":"x &= ~(1 << 2);\n"},{"title":"card_52","front":"What is a Binary Search Tree?","back":"A binary tree is a data structure where each node has a comparable key and satisfies the restriction that the key in any node is larger than the keys in all nodes in that node's left subtree and smaller than the keys in all nodes in that node's right subtree.\n"},{"title":"card_53","front":"What is an AVL tree?","back":"A BST where the height of every node and that of its sibling differ by at most 1.\n"},{"title":"card_54","front":"What is a red-black tree?","back":"BSTs having red and black links satisfying:\n- Red links lean left\n- No node has two links connected to it\n- The tree has perfect black balance: every path from the root to a null link has the same number of blacks\n"},{"title":"card_55","front":"What is a splay tree?","back":"A self-adjusting binary search tree where recently accessed elements are moved to the root so they are quick to access again.\n"},{"title":"card_56","front":"What is a treap?","back":"A random priority is assigned to every key and must maintain two properties:\n-They are in order with respect to their keys, as in a typical binary search tree\n-They are in heap order with respect to their priorities, that is, no key has a key of lower priority as an ancestor\nO(log N) expected time for all operations, O(N) worst case.\n"},{"title":"card_57","front":"What is typical cache line size?","back":"64 bytes.\n\n-- extra below --\n\nTo know the sizes, you need to look it up using the documentation for the processor, afaik there is no programatic way to do it. On the plus side however, most cache lines are of a standard size, based on intels standards. On x86 cache lines are 64 bytes, however, to prevent false sharing, you need to follow the guidelines of the processor you are targeting (intel has some special notes on its netburst based processors), generally you need to align to 64 bytes for this (intel states that you should also avoid crossing 16 byte boundries).\n\nTo do this in C or C++ requires that you use aligned_malloc or one of the compiler specific specifiers such as __attribute__((align(64))) or __declspec(align(64)). To pad between members in a struct to split them onto different cache lines, you need on insert a member big enough to align it to the next 64 byte boundery\n"},{"title":"card_58","front":"What is latency?","back":"Latency is the delay from input into a system to desired outcome. The time interval between between a stimulus and response.\n"},{"title":"card_59","front":"What is a y-fast trie?","back":"A y-fast trie is a data structure for storing integers from a bounded domain. It supports exact and predecessor or successor queries in time O(log log M), using O(n) space, where n is the number of stored values and M is the maximum value in the domain. The structure was proposed by Dan Willard in 1982 to decrease the O(n log M) space used by an x-fast trie.\n"},{"title":"card_60","front":"What is an x-fast trie?","back":"An x-fast trie is a data structure for storing integers from a bounded domain. It supports exact and predecessor or successor queries in time O(log log M), using O(n log M) space, where n is the number of stored values and M is the maximum value in the domain. The structure was proposed by Dan Willard in 1982, along with the more complicated y-fast trie, as a way to improve the space usage of van Emde Boas trees, while retaining the O(log log M) query time.\n"},{"title":"card_61","front":"What is a van Emde Boas tree?","back":"The van Emde Boas tree supports insertions, deletions, lookups, successor queries, and predecessor queries in time O(log log U), where U is the universe of items to store. Items are stored in clusters of size sqrt(U). \n\nThe van Emde Boas data structure divides the range {0,...,n−1} into blocks of size sqrt(n), which we call clusters. Each cluster is itself a vEB structure of size sqrt(n). In addition, there is a “summary” structure that keeps track of which clusters are nonempty.\n\nMore detail:\nA van Emde Boas tree (or van Emde Boas priority queue), also known as a vEB tree, is a tree data structure which implements an associative array with m-bit integer keys. It performs all operations in O(log m) time, or equivalently in O(log log M) time, where M = 2m is the maximum number of elements that can be stored in the tree. The M is not to be confused with the actual number of elements stored in the tree, by which the performance of other tree data-structures is often measured. The vEB tree has good space efficiency when it contains a large number of elements, as discussed below. It was invented by a team led by Dutch computer scientist Peter van Emde Boas in 1975.\n"},{"title":"card_62","front":"What is a compressed trie?","back":"It's a trie where the non-branching paths are compacted into a single edge.\n"},{"title":"card_63","front":"What relationship of the keys do you lose with a hash table?","back":"The ordering of the keys.\n"},{"title":"card_64","front":"Sed command to take a file separated by spaces, turn spaces into newlines, and then sort it alphabetically.","back":"sed 's/ /\n/g' words.txt | sort\n"},{"title":"card_65","front":"Print columns 2, 3, and 6 from the date command.","back":"date | awk '{print $2, $3, $6}'\n"},{"title":"card_66","front":"Take a file delimited by : and make it tab-delimited.","back":"cat /etc/passwd | sed 's/:/\t/g'\n"},{"title":"card_67","front":"Output a file with line numbers.","back":"cat -n somefile\n"},{"title":"card_68","front":"Is quicksort stable?","back":"No.\n"},{"title":"card_69","front":"Can quicksort be done in-place?","back":"Yes.\n"},{"title":"card_70","front":"Can merge sort be done in-place?","back":"No. It requires O(n) space. There is an in-place version?\n"},{"title":"card_71","front":"Is merge sort stable?","back":"Yes.\n"},{"title":"card_72","front":"Is insertion sort stable?","back":"Yes.\n"},{"title":"card_73","front":"Can insertion sort be done in-place?","back":"Yes.\n"},{"title":"card_74","front":"Can selection sort be done in-place?","back":"Yes.\n"},{"title":"card_75","front":"Is selection sort stable?","back":"No.\n"},{"title":"card_76","front":"Is heap sort stable?","back":"No.\n"},{"title":"card_77","front":"Can heap sort be done in-place?","back":"Yes.\n"},{"title":"card_78","front":"In what case would perfect hashing be practical?","back":"When you don't need to support inserts or deletes. The data is static.\n"},{"title":"card_79","front":"How does perfect hashing handle collisions?","back":"It creates a second hash table in the buckets where there are multiple items (k), using a second hash function, and k^2 space. The hash table has two hashing levels. k^2 is chosen because the Markov inequality (birthday paradox) ensures we will not have collisions in bucket.\n"},{"title":"card_80","front":"What is the optimal load factor for a hash table?","back":"O(sqrt(n))\n"},{"title":"card_81","front":"What is the expected load factor for a hash table?","back":"n/m, where n = items, m = buckets) n/m is also called alpha.\n"},{"title":"card_82","front":"What is the technical running time for operations on a hash table?","back":"O(1 + alpha), where alpha is the load factor (n/m). Table doubling operations are amortized.\n"},{"title":"card_83","front":"What is the worst-case search time of perfect hashing?","back":"O(1)\n"},{"title":"card_84","front":"What is the worst-case space required for perfect hashing?","back":"O(n)\n"},{"title":"card_85","front":"What's the best-case running time of binary search?","back":"O(1) - we get lucky and find the element right at the midpoint.\n"},{"title":"card_86","front":"What's the worst-case running time of binary search?","back":"O(log n)\n"},{"title":"card_87","front":"What are the downsides of using an adjacency matrix to represent a graph?","back":"Finding all the outgoing edges from a vertex takes O(n) time even if there aren't very many, and the O(n^2) space cost is high for \"sparse graphs,\" those with much fewer than n^2 edges.\n"},{"title":"card_88","front":"When is using an adjacency list expensive?","back":"Finding predecessors of a node u is extremely expensive, requiring looking through every list of every node in time O(n + e), where e is the total number of edges, although if this is something we actually need to do often we can store a second copy of the graph with the edges reversed.\n"},{"title":"card_89","front":"When are adjacency lists most useful?","back":"Adjacency lists are most useful when we mostly want to enumerate outgoing edges of each node. This is common in search tasks, where we want to find a path from one node to another or compute the distances between pairs of nodes. If other operations are important, we can optimize them by augmenting the adjacency list representation; for example, using sorted arrays for the adjacency lists reduces the cost of edge existence testing to O(log(d+ (u))), and adding a second copy of the graph with reversed edges lets us find all predecessors of u in O(d− (u)) time, where d− (u) is u's in-degree.\n"},{"title":"card_90","front":"What is the space required for a graph using an adjacency list?","back":"O(n + e)\n"},{"title":"card_91","front":"What's the maximum unsigned number you can represent with 4 bits?","back":"15\n"},{"title":"card_92","front":"What's the maximum unsigned number you can represent with 8 bits?","back":"255\n"},{"title":"card_93","front":"What's the maximum unsigned number you can represent with 16 bits?","back":"65,535\n"},{"title":"card_94","front":"What's the maximum unsigned number you can represent with 6 bits?","back":"63\n"},{"title":"card_95","front":"What's the maximum unsigned number you can represent with 15 bits?","back":"32,767\n"},{"title":"card_96","front":"What's the maximum signed number you can represent with 4 bits?","back":"7\n"},{"title":"card_97","front":"What's the maximum signed number you can represent with 16 bits?","back":"32,767\n"},{"title":"card_98","front":"What's the maximum signed number you can represent with 8 bits?","back":"127\n"},{"title":"card_99","front":"What's the maximum signed number you can represent with 9 bits?","back":"255\n"},{"title":"card_100","front":"What's the maximum unsigned number you can represent with 32 bits?","back":"4.294 Billion\n"},{"title":"card_101","front":"What's the maximum signed number you can represent with 32 bits?","back":"2.147 Billion\n"},{"title":"card_102","front":"How do you get the logarithm of a number n given a base b?","back":"Keep dividing n by b until you get to a number <= 1.\n"},{"title":"card_103","front":"How can you write log(base b)(ac)?","back":"log(base b)a + log(base b)c\n"},{"title":"card_104","front":"How can you write log(base b)(a/c)?","back":"log(base b)a - log(base b)c\n"},{"title":"card_105","front":"How else can you write log(base b)(a^c)?","back":"c * log(base b)a\n"},{"title":"card_106","front":"How you can express log(base b)a as another base?","back":"log(base d)a / log(base d)b\n"},{"title":"card_107","front":"Why is log(base2)(2^n) == n?","back":"log(base2)(2^n) = n * log(base 2)2 = n * 1 = n\n"},{"title":"card_108","front":"What is the arithmetic series: 1 + 2 + 3 + 4 + ... (n - 1) + n?","back":"(n(n+1)) / 2\n"},{"title":"card_109","front":"What is the value of the geometric (exponential) series when x != 1: 1 + x + x^2 + x^3 + ... x^n ?","back":"(x^(n + 1) - 1) / (x - 1)\n"},{"title":"card_110","front":"What is the sum of this series when it's infinite and x < 1? 1 + x + x^2 + x^3 + ... x^n ?","back":"1 / (1 - x)\n"},{"title":"card_111","front":"What is the sum of the harmonic series for the nth harmonic number: 1 + 1/2 + 1/3 + 1/4 .. + 1/n","back":"No closed form, only good approximations:\n\n≈ 0.57721\nthe Euler-Mascheroni constant.\n"},{"title":"card_112","front":"What is the maximum unsigned integer you can represent with n bits?","back":"2^n - 1\n"},{"title":"card_113","front":"Given a fully balanced binary tree with x nodes, what is the height of the tree in nodes?","back":"log(base2) x + 1\n"},{"title":"card_114","front":"Given a fully balanced k-ary tree with x nodes, what is the height of the tree in nodes?","back":"log(basek) x + 1\n"},{"title":"card_115","front":"A binary tree with height h can contain at most how many nodes?","back":"2^(h+1) − 1 nodes\n"},{"title":"card_116","front":"For a k-ary tree with height h, the upper bound for the maximum number of leaves is:","back":"k^h\n"},{"title":"card_117","front":"What is the complexity of Dijkstra's shortest-path algorithm?","back":"O(e log v), where e is the number of edges. \nIt must scan each edge, and gets and updates values on the heap.\n"},{"title":"card_118","front":"What is a drawback of using an adjacency matrix for an undirected graph?","back":"Half of the entries in the matrix are duplicates.\n"},{"title":"card_119","front":"What is the memory needed to store an adjacency list?","back":"Theta( |V| + |E| )\n"},{"title":"card_120","front":"What is the memory needed to store an adjacency matrix?","back":"Theta(|V|^2)\n"},{"title":"card_121","front":"How would you implement a queue with a linked list?","back":"Use a tail pointer. Push new items at the tail, pop items at the head. Both operations are constant-time.\n"},{"title":"card_122","front":"How would you implement a stack with a linked list?","back":"Push and pop items at the head. Both operations are constant-time.\n"},{"title":"card_123","front":"What preference of nodes vs leaves does preorder traversal give on a tree?","back":"Nodes first, leaves later.\n"},{"title":"card_124","front":"What preference of nodes vs leaves does postorder traversal give on a tree?","back":"Leaves first, internal nodes later.\n"},{"title":"card_125","front":"What could you use in DFS to turn a recursive algorithm into an interative one?","back":"A stack.\n"},{"title":"card_126","front":"What do you use to keep track of nodes to visit in BFS?","back":"A queue.\n"},{"title":"card_127","front":"Using a stack to keep track of unvisited nodes gives what kind of traversal?","back":"DFS\n"},{"title":"card_128","front":"Using a queue to keep track of unvisited nodes gives what kind of traversal?","back":"BFS\n"},{"title":"card_129","front":"In a highly connected graph of n vertices, how many cycles can there be?","back":"(n - 1)! - enumerating is possible (using backtracking), but there will be a lot.\n"},{"title":"card_130","front":"What can use to find if a graph is bipartite?","back":"BFS. Using only 2 colors. When you encounter a new vertex, if it has no color, give it the opposite color of its parent vertex. If it is already colored the same, the graph is not bipartite.\n"},{"title":"card_131","front":"How can you find a cycle in a graph?","back":"DFS. If you discover an edge that connects to an ancestor (previously discovered vertex), you have a cycle.\n"},{"title":"card_132","front":"What is an articulation vertex?","back":"A vertex of a graph whose deletion disconnects the graph.\n"},{"title":"card_133","front":"How can you find an articulation vertex?","back":"DFS multiple times. Remove each edge one at a time, doing a DFS after each, so see if you end up with > 1 connected components. If you remove a node and then DFS and find you have fewer than m - 1 edges, you've deleted an articulation vertex. O(n(n+m))\n\nA faster way, with a little more bookkeeping, can be done in O(n+m) time, if you do DFS and keep track of parents and make a note when you reach a back edge, which connects to an ancestor.\n"},{"title":"card_134","front":"How could you identify errors in a DNA fragment assembly given many pairs of sequences, where item A must appear before B in the larger sequence?","back":"Build a DAG representing all the left-right constraints. Any topological sort of the DAG is a consistent ordering. If there are cycles, there must be errors.\n"},{"title":"card_135","front":"What path does BFS find in a graph?","back":"The shortest path tree from start to all nodes (unweighted)\n"},{"title":"card_136","front":"What's the upper bound on the number of edges in a graph G(V, E)?","back":"|V|^2\n"},{"title":"card_137","front":"In Python, initialize a list of lists called x with 100 elements.","back":"x = [[] for _ in range(100)]\n"},{"title":"card_138","front":"What is the optimal substructure property tell us about shortest paths?","back":"That a subpath of a shortest path is also a shortest path.\n"},{"title":"card_139","front":"What is a Dunder method?","back":"A magic method in Python, such as __getitem__ and __len__.\n"},{"title":"card_140","front":"What is the sum of numbers from 1 to 2^n?","back":"2^(n+1) - 1\nThe sum of a sequence of powers is roughly equal to the next value in the sequence.\n"},{"title":"card_141","front":"How many ways can you rearrange a string of n unique characters?","back":"n!\nPermutations.\n"},{"title":"card_142","front":"How many ways can you arrange k characters from n unique characters?","back":"n! / (n - k)!\nPermutation of n elements of size k.\n"},{"title":"card_143","front":"How many subsets (ordering doesn't matter) of size k are there in n unique characters?","back":"n! / k!(n - k)!\nThis is n choose k.\n"},{"title":"card_144","front":"What should you avoid in your base case in recursion?","back":"Too many base case scenarios. Just have one base case so you can return as quickly as possible. Avoid \"arm's length\" recursion.\n"},{"title":"card_145","front":"What is the bandwidth of a graph?","back":"The longest edge in the permutation that gives you the shortest edges.\n"},{"title":"card_146","front":"When talking dynamic programming, what is feasibility?","back":"The rules the algorithm must adhere to in reaching its solution.\n"},{"title":"card_147","front":"When talking dynamic programming, what is optimality?","back":"An algorithm has optimality if the subsolutions of an optimal solution of the problem are themsleves optimal solutions for their subproblems.\n"},{"title":"card_148","front":"What is dynamic programming?","back":"Dynamic programming is a general-purpose algorithm design technique that is most often used to solve combinatorial optimization problems, where we are looking for the best possible input to some function chosen from an exponentially large search space.\n\nThere are two parts to dynamic programming. The first part is a programming technique: dynamic programming is essentially divide and conquer run in reverse: we solve a big instance of a problem by breaking it up recursively into smaller instances; but instead of carrying out the computation recursively from the top down, we start from the bottom with the smallest instances of the problem, solving each increasingly large instance in turn and storing the result in a table. The second part is a design principle: in building up our table, we are careful always to preserve alternative solutions we may need later, by delaying commitment to particular choices to the extent that we can.\n\nThe bottom-up aspect of dynamic programming is most useful when a straightforward recursion would produce many duplicate subproblems. It is most efficient when we can enumerate a class of subproblems that doesn't include too many extraneous cases that we don't need for our original problem.\n"},{"title":"card_149","front":"What is the complexity for a naive recursive Fibonacci function?","back":"Θ(φ^n), where phi(φ) is the golden ratio (1 + sqrt(5)) / 2. \napprox: 1.618\n"},{"title":"card_150","front":"What does __getitem__ in a class allow us to use?","back":"- iteration\n- slicing\n- reverse iteration\n- random.choice\n"},{"title":"card_151","front":"How many subsets are there in n items?","back":"2^n\n"},{"title":"card_152","front":"What is a contiguously-allocated structures, and give examples.","back":"Contiguously-allocated structures are composed of single slabs of memory, and include arrays, matrices, heaps, and hash tables.\n"},{"title":"card_153","front":"What are linked data structures and give examples.","back":"Linked data structures are composed of distinct chunks of memory bound together by pointers, and include lists, trees, and graph adjacency lists.\n"},{"title":"card_154","front":"What are some benefits of arrays?","back":"- Constant-time access given the index\n- Space efficiency\n- Memory locality\n"},{"title":"card_155","front":"Why is memory locality important?","back":"Physical continuity between successive data accesses helps exploit the high-speed cache memory on modern computer architectures.\n"},{"title":"card_156","front":"What are some advantages to linked lists over arrays?","back":"- Overflow on linked structures can never occur unless the memory is actually full.\n- Insertions and deletions are simpler than for contiguous (array) lists.\n- With large records, moving pointers is easier and faster than moving the items themselves.\n"},{"title":"card_157","front":"What are some advantages to arrays over linked lists?","back":"- Linked structures require extra space for storing pointer fields.\n- Linked lists do not allow efficient random access to items.\n- Arrays allow better memory locality and cache performance than random pointer jumping.\n"},{"title":"card_158","front":"Codeless question: Write a function to find the middle node of a singly-linked list.","back":"How would you do it?\n"},{"title":"card_159","front":"Codeless question: Write a function to compare whether two binary trees are identical. Identical trees have the same key value at each position and the same structure.","back":"How?\n"},{"title":"card_160","front":"Codeless quesiton: Write a program to convert a binary search tree into a linked list.","back":"How would you do it?\n"},{"title":"card_161","front":"Codeless Question: You are given a search string and a magazine. You seek to generate all the characters in search string by cutting them out from the magazine. Give an algorithm to efficiently determine whether the magazine contains all the letters in the search string.","back":"How would you do it?\n"},{"title":"card_162","front":"Codeless question: Give an algorithm for finding an ordered word pair (e.g., “New York”) occurring with the greatest frequency in a given webpage. Which data structures would you use?","back":"You could use a hash table, creating or updating an entry for each pair. \nKeep track of max_frequency and most_frequent_phrase.\nJust increment the count, and when you see the new count is > than max_frequency, update max_frequency and most_frequent_phrase\n"},{"title":"card_163","front":"Codeless question: Given a set of n numbers, how do you find the pair of numbers that have the smallest difference between them?","back":"Sort them: Once the numbers are sorted, the closest pair of numbers must lie next to each other somewhere in sorted order. Thus, a linear-time scan through them completes the job, for a total of O(n log n) time including the sorting.\n"},{"title":"card_164","front":"Codeless question: Are there any duplicates in a given set of n items?","back":"This is a special case of the closest-pair problem, where we ask if there is a pair separated by a gap of zero. The most efficient algorithm sorts the numbers and then does a linear scan though checking all adjacent pairs.\n"},{"title":"card_165","front":"Codeless question: Given a set of n items, which element occurs the largest number of times in the set? Bonus: How do you find out how many times some element k appears?","back":"If the items are sorted, we can sweep from left to right and count them, since all identical items will be lumped together during sorting.\n\nTo find out how often an arbitrary element k occurs, look up k using binary search in a sorted array of keys. Then use binary search in each direction to find where that run of the number begins and ends.\n"},{"title":"card_166","front":"Codeless question: Give an efficient algorithm to determine whether two sets (of size m and n, respectively) are disjoint.","back":"The small set can be sorted in O(m log m) time. We can now do a binary search with each of the n elements in the big set, looking to see if it exists in the small one. The total time will be O((n + m) log m).\n\nThis is better than sorting the larger array or sorting both sets and going through the list.\n"},{"title":"card_167","front":"What is a uniform distribution?","back":"When a known finite number of outcomes are equally likely to occur. When graphed as a histogram of occurrences, it's a flat line. N items each have 1/n probability.\n"},{"title":"card_168","front":"What is a normal distribution?","back":"The standard normal probability density function has the famous bell shape that is known to just about everyone.\n"},{"title":"card_169","front":"What is an n-gram?","back":"A set of N sequential words appearing together.\n"},{"title":"card_170","front":"What's the maximum unsigned number you can represent with 9 bits?","back":"511\n"},{"title":"card_171","front":"Whats the average height of a binary search tree after n insertions?","back":"2 ln n\nAbout 39% taller than a perfectly balanced BST\n"},{"title":"card_172","front":"What is the runtime of randomized quicksort?","back":"Theta(n log n) time on any input, with high probability.\n"},{"title":"card_173","front":"Python: Default arguments are okay to use with the following caveat.","back":"Do not use mutable objects as default values in the function or method definition.\n\nLists are not ok.\n"},{"title":"card_174","front":"Python: Give an example of a conditional expression.","back":"x = 1 if cond else 2\n"},{"title":"card_175","front":"Python: break this string 'a/b/c' into a list of ['a', 'b', c']","back":"'a/b/c'.split('/')\n"},{"title":"card_176","front":"Python: split a word or sentences into characters.","back":"list('some words')\n"},{"title":"card_177","front":"What's the difference between foo.sort() and sorted(foo) where foo is a list?","back":"foo.sort() changes the list to its sorted state\nsorted(foo) doesn't change foo, just returns a sorted list.\n"},{"title":"card_178","front":"Can you sort a tuple?","back":"Yes, using sorted(foo)\nbut not with foo.sort()\n"},{"title":"card_179","front":"Python: How would you remove indices 6 to 11 in a list foo?","back":"del foo[6:12]\n"},{"title":"card_180","front":"Python: How can you tell if an index is in a list?","back":"if 0 < i < len(foo):\n"},{"title":"card_181","front":"What's the probability of getting heads twice? P(HH)","back":"1/4 \n= 1/2 * 1/2\n"},{"title":"card_182","front":"What's the probability of getting heads, tails, heads? P(HTH)","back":"1/8 \n= 1/2 * 1/2 * 1/2\nthe ordering of HTH doesn't matter. It could be TTH or HHH or TTT, they are tall the same.\n"},{"title":"card_183","front":"What's the probability of getting heads 200 times in a row?","back":"(1/2)^200\n"},{"title":"card_184","front":"What's the Probability of getting head, tails or tails, heads? P(HT U TH)","back":"(1/2 * 1/2) + (1/2 * 1/2) = 2/4 = 1/2\n"},{"title":"card_185","front":"What's the probability of getting exactly 3 heads in 8 flips?","back":"56/256 = 7/32\n\n(8 choose 3)/2^8\n"},{"title":"card_186","front":"You have 26 letters in an alphabet. How many ways you can arrange 3 letters from that alphabet where repeated letters is OK?","back":"26*26*26 = 26^3 = 17,576\n"},{"title":"card_187","front":"You have 26 letters in an alphabet. How many ways you can arrange 3 letters from that alphabet without repeating a letter?","back":"26*25*24 = 26 permute 3 = 15,600\n"},{"title":"card_188","front":"Given an alphabet of 26 letters, how many times you can you choose 3 letters, if ordering of the letters doesn't matter?","back":"26*25*24 / 3! = 2600\n"},{"title":"card_189","front":"What is 0! ?","back":"1\n"},{"title":"card_190","front":"There are 4 people. How many ways can they shake each other's hands without shaking the same person's hand twice?","back":"6\n= 4 choose 2\n= 4 * 3 / 2\n"},{"title":"card_191","front":"Right-propagate the rightmost 1-bit, producing all 1's if x = 0 (e.g., 01011000 01011111):","back":"x |= (x - 1)\n"},{"title":"card_192","front":"Isolate the right-most bit in x.","back":"x & ~(x - 1)\n"},{"title":"card_193","front":"What is P?","back":"The set of all problems solvable in polynomial time.\n"},{"title":"card_194","front":"What is EXP?","back":"The set of all problems solvable in exponential time.\n"},{"title":"card_195","front":"What is R? (not real numbers)","back":"The set of problems solvable in finite time.\n"},{"title":"card_196","front":"Is the Halting Problem in R?","back":"No.\n"},{"title":"card_197","front":"What does NP mean? What is an NP algorithm?","back":"NP is the set of decision problem solvable in non-deterministric polynomial time. An NP problem can be solved by a lucky algorithm that magically always finds a yes decision. NP problems can be checked in polynomial time.\n"},{"title":"card_198","front":"What makes a problem NP-Complete?","back":"If x is an element of NP and of NP-hard. NP-Complete is the narrow intersection of NP and NP-hard.\n\nBecause NP is such a large class of problems, most NP-hard problems you encounter will actually be complete.\n"},{"title":"card_199","front":"What is Fib(0) ?","back":"0\n"},{"title":"card_200","front":"What is Fib(3) ?","back":"2\n"},{"title":"card_201","front":"What is Fib(2) ?","back":"1\n"},{"title":"card_202","front":"What is a PTAS?","back":"Polynomial-time approximation scheme.\n"},{"title":"card_203","front":"What is a pointer?","back":"A memory address stored in memory.\n"},{"title":"card_204","front":"Give 2 examples of common data structures that contain reference cycles.","back":"- Doubly-linked lists\n- Trees with parent and child pointers\n"},{"title":"card_205","front":"What is a weak reference in Python?","back":"A weak reference to an object does not affect its reference count. \nWhen the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.\n"},{"title":"card_206","front":"How does garbage collection work in CPython?","back":"CPython uses reference counting and generational garbage collection. There are 3 age stages where objects live in memory. They all start in the \"nursery\", stage0, then if they survive a garbage collection, they are moved to stage1, the oldest objects that continue to survive in stage1 are promoted to stage2. The gc module has thresholds 700, 10, 10 for each stage. In order to decide when to run, the collector keeps track of the number object allocations and deallocations since the last collection. When the number of allocations minus the number of deallocations exceeds threshold0, collection starts. If generation 0 has been examined more than threshold1 times since generation 1 has been examined, then generation 1 is examined as well. Similarly, threshold2 controls the number of collections of generation 1 before collecting generation 2.\n"},{"title":"card_207","front":"What is reference counting?","back":"RC is a method of garbage collection. The runtime keeps track of references to an object by manipulating the reference count on each assignment and delete (del), and when the reference count reaches 0 it means the object is practically unreachable. When the next collection runs, the object's memory will be reserved to allocate for new objects.\n"},{"title":"card_208","front":"What is a finalizer in Python?","back":"A finalizer is a destructor, named __del__. __del__() is run when the runtime is about to destroy the object.\n"},{"title":"card_209","front":"What are 2 advantages of reference counting?","back":"- easy to implement\n- collects garbage incidentally without large pauses in execution.\n"},{"title":"card_210","front":"What are 2 disadvantages of reference counting?","back":"- it cannot collect circular references\n- manipulating reference counts at each assignment is very slow.\n"},{"title":"card_211","front":"What is cyclic garbage collection?","back":"Detects and removes cycles unreachable by the program.\n"},{"title":"card_212","front":"How is garbage collection done in PyPy?","back":"The GC implementation can be chosen at runtime. It's pluggable.\nPyPy uses mark and sweep, and generational gc optimization. Marked objects are promoted from the nursery to an older generation.\nPyPy uses incremental garbage collection, where major collection is split into multiple passes, each lasting only a few milliseconds.\n"},{"title":"card_213","front":"What is a pointer?","back":"A pointer is a memory address stored in memory.\n"},{"title":"card_214","front":"How does mark and sweep work?","back":"(In Java) Perform a DFS on the graph of references to objects. This graph can have multiple roots. Each root is a reference that the program can access directly, such as a variable. Traverse the graph, setting a mark bit in each object. The sweep phase causes unmarked memory to be linked together in a list, so that memory can be reallocated. Sometimes this also triggers compaction, which moves used objects adjacent to each other in memory. The side effect of this is that free memory is also adjacent to free memory so large blocks can be allocated.\n"},{"title":"card_215","front":"What is copying garbage collection (stop and copy)?","back":"Heap memory is split into 2 partitions: an old space and a new space. Find live objects by DFS of their reference graph, and move live objects into the new space. The new space is now called the old space. Unreachable objects are simply left in the old space to be overwritten the next time collection occurs. The movement of objects implicitly compacts the objects. Disadvantage: you can only use half of the heap space.\n"},{"title":"card_216","front":"How could you implement an LRU cache?","back":"A fast lookup table, like a hash table or binary tree, and a linked list of items by use. When you access or add an item, you delete it from the linked list and add it to the head of the list. Then to prune, traverse the linked list and remove trailing elements, and delete them from the storage (tree or hash table).\nYou can also use a splay tree, since it moves accesses to the root. To prune items, somehow find and remove the leaves, since the number of leaves will be about n/2.\n"},{"title":"card_217","front":"What is a direct mapped cache?","back":"It's a type of cache used in the CPU, where the lower order bits of a given memory address are used modulo the number of cache lines to place or lookup in the cache. Collisions are treated as overwrites.\n"},{"title":"card_218","front":"What is a fully-associative cache?","back":"It's a type of cache used in the CPU, where lookups are done on all cache lines in parallel to determine a hit or miss.\n\nThis requires a very large number of comparators that increase the complexity and cost of implementing large caches. Therefore, this type of cache is usually only used for small caches, typically less than 4K.\n"},{"title":"card_219","front":"Disadvantage of a fully-associative cache?","back":"- expensive due to parallel checks\n- complexity of implementing this scheme\n"},{"title":"card_220","front":"How do some processors handle caching for data and instructions?","back":"There will be a slightly slower (3-4 clocks latency) separate cache for data.\n"},{"title":"card_221","front":"What is an N-way set associative cache?","back":"A Set-Associative cache scheme is a combination of Fully-Associative and Direct Mapped caching schemes. A set-associate scheme works by dividing the cache SRAM into equal sections (2 or 4 sections typically) called cache ways. The cache page size is equal to the size of the cache way. Each cache way is treated like a small direct mapped cache.\n"},{"title":"card_222","front":"Describe the memory hierarchy of a Core i7 processor.","back":"Inside of each core is a 32 kB L1 instruction cache, a 32 kB L1 data cache (it's 8-way set associative), and a dedicated 256 kB L2 cache (also 8-way set associative). \nOutside of the cores is the L3, which is much larger at 8 MB and smarter (16-way associative) than the L2s.\n"},{"title":"card_223","front":"When is entropy at its maximum?","back":"When all outcomes are equal.\n"},{"title":"card_224","front":"As predictability increases, what happens to entropy?","back":"It decreases.\n"},{"title":"card_225","front":"As it relates to compression, as entropy increases, does our ability to compress increase?","back":"No, it decreases.\n"},{"title":"card_226","front":"What does low entropy mean?","back":"Very predictable.\n"},{"title":"card_227","front":"What is entropy?","back":"The minimum number of bits needed to represent x number of states. Also, information we don't know.\n"},{"title":"card_228","front":"What is a Caesar cipher?","back":"The cipher created by shifting/rotating an alphabet by a specific number previously agreed upon.\n"},{"title":"card_229","front":"What is a polyalphabetic cipher?","back":"A cipher where each letter is shifted based on the shifts of letters in a key word.\n"},{"title":"card_230","front":"What is the entropy of n equally likely outcomes?","back":"log(n)\n"},{"title":"card_231","front":"Is GET idempotent?","back":"Yes\n"},{"title":"card_232","front":"Is PUT idempotent?","back":"Yes.\n"},{"title":"card_233","front":"Is POST idempotent?","back":"No.\n"},{"title":"card_234","front":"Is DELETE idempotent?","back":"According to the REST spec, yes, but it's up to the developer to conform to that. It can be achieved by using a deleted flag for a resource instead of completely removing the resource.\n"},{"title":"card_235","front":"What is idempotent?","back":"The property that a method has side-effects of making more than one identical requests is the same as for a single request.\n"},{"title":"card_236","front":"What is HMAC?","back":"HMAC is a keyed-hash message authentication code used to provide a checksum for a message, sent along with the message to provide confidence that the message has not been tampered.\n"},{"title":"card_237","front":"What is a MAC?","back":"MAC is a message authentication code used to provide a checksum for a message, sent along with the message to provide confidence that the message has not been tampered.\n"},{"title":"card_238","front":"How does RSA work?","back":"It's a public/private key cryptography method. The public key can be used to encrypt a message into ciphertext that only the owner of the key can decrypt. The owner of the key uses their secret key to encrypt messages, and their secret key to decrypt messages encrypted with their public key.\n"},{"title":"card_239","front":"What is the phi function?","back":"It answers the number of integers <= n that do not share a common factor with n.\n"},{"title":"card_240","front":"What is phi(n) if n is prime?","back":"n - 1\n"},{"title":"card_241","front":"What is the gcd of a number a and prime p when p is prime?","back":"1, unless a is a pseudoprime (Carmichael number)\n"},{"title":"card_242","front":"What does SHA stand for?","back":"One of the family of Secure Hashing Algorithms.\n"},{"title":"card_243","front":"What is the largest output size of SHA-3?","back":"512 bits\n"},{"title":"card_244","front":"What are desirable properties of one-way functions?","back":"- collision resistant\n- target collision resistant\n- non-malleable\n"},{"title":"card_245","front":"If a one-way function is collision-resistant, does that mean it's also target collision-resistant?","back":"Yes.\n"},{"title":"card_246","front":"If a one-way function is target collision-resistant, does that mean it's also collision-resistant?","back":"No.\n"},{"title":"card_247","front":"What is symmetric key encryption?","back":"There is a known encryption function, and one key is used to encrypt and decrypt. The key has to be shared between 2 parties.\n"},{"title":"card_248","front":"How does Diffie-Hellman key exchange work?","back":"2 parties agree on a G and a modulus p, and each party comes up with a number. One party does G^a and the other G^b. They pass this information. One party A computes the key from B as B^a mod p. B computes A^b mod p to get the key.\n"},{"title":"card_249","front":"Is Diffie-Hellman key exchange perfect?","back":"No. A man in the middle can intercept one side, and communicate with parties A and B independently.\n"},{"title":"card_250","front":"How is RSA (using product of large primes) better than using NP-Complete algorithms for encryption?","back":"NP-Complete algorithms are hard in the worst case, but can be sometimes solved in linear time in the average case. Compositing the product of large primes is hard in the average case.\n"},{"title":"card_251","front":"What is Vigenere cipher?","back":"Improvement on Caesar cipher. Letters are shifted based on a shifted dictionary. \"Polyalphabetic cipher\"\n"},{"title":"card_252","front":"What is a one-time pad encryption?","back":"The \"perfect\" simple encryption scheme. Pad/key is the same size as the message being encrypted. The key is randomly generated and xored against the plain text. Or key used to determine the amount each letter should be shifted.\n"},{"title":"card_253","front":"What is block size in cryptography?","back":"Symmetric key ciphers are generally divided into stream ciphers and block ciphers. Block ciphers operate on a fixed length string of bits. The length of this bit string is the block size. Both the input (plaintext) and output (ciphertext) are the same length; the output cannot be shorter than the input – this is logically required by the Pigeonhole principle and the fact that the cipher must be invertible – and it is simply undesirable for the output to be longer than the input.\n"},{"title":"card_254","front":"What is the limiting factor of compression?","back":"For lossless compression, it's entropy. For lossy compression, it's our acceptance with the amount of loss.\n"},{"title":"card_255","front":"What is LZ* compression based on?","back":"Cataloging the positions and lengths of redundant patterns and combining the values with a dictionary.\n"},{"title":"card_256","front":"What is LZMA?","back":"It's a variant of LZ77 that uses Markov chains. It's used in the 7z compression algorithms used in 7-zip.\n"},{"title":"card_257","front":"What is DEFLATE?","back":"It's an lossless compression algorithm based on LZ77 used in Gzip, WinZip, and mod_deflate, which is bundled with Apache web server for automated gzip compression of HTTP served content. It uses LZ77 and Huffman coding.\n"},{"title":"card_258","front":"How does LZ77-based compression work?","back":"LZ77 is a dictionary encoding algorithm, which is a statistical encoding algorithm. Compression in the LZ77 algorithm is based on the notion that strings of characters (words, phrases, etc.) occur repeatedly in the message being compressed.\n\nThe input is partitioned into 2 segments: a search buffer and a look-ahead buffer. The search buffer maxes out at 32KB. Starting with one character in the LA buffer, it looks back in the search buffer to find a copy of the symbol. If one is found, it looks at the second symbol of the LA buffer to see if it also matches the predecessor. Using this method, it can detect long phrases of symbols and encode them as one unit.\n\nThis process implicitly creates a rolling statistical probability for each symbol/phrase.\n"},{"title":"card_259","front":"What is Huffman encoding?","back":"Huffman encoding algorithm analyzes the occurrence of individual symbols and creates a binary tree where the common symbols are closest to the root, using fewer bits to encode, and less common/rare symbols have longer paths on the tree, with longer encodings to accommodate. By traversing the tree, from root to leaf, and keeping track of 1 or 0 at each node, we can determine the encoding of the symbol.\n"},{"title":"card_260","front":"What is the primary factor of compression?","back":"Probability of redundant portions of input.\n"},{"title":"card_261","front":"How can you maximize compression?","back":"By deeply analyzing the given input to reduce redundancy as much as possible.\n"},{"title":"card_262","front":"What compression scheme uses Burrows-Wheeler transform?","back":"BZip2\n"},{"title":"card_263","front":"What is the Burrows-Wheeler transform?","back":"It's a compression method involving the sorting of all possible rotations of the input text into lexicographic order. Take as output the last column and the index of the row that the original text appears in. \n\nTo decode, take the single column and repeatedly add the final columns characters to each of the rows, sorting each time. Once you've reached the length of the column's height, use the index to find the output string.\n"},{"title":"card_264","front":"For Gzip in web servers, what is the usual setting?","back":"6\n"},{"title":"card_265","front":"What is the min and max compression settings in command line gzip?","back":"0-9\n"},{"title":"card_266","front":"How can you make JSON better compressable with Gzip?","back":"Transpose from multiple mini-dicts into one dict with arrays as the values. This allows the items in an array to fit within the 32KB search buffer common to LZ-based compression.\n"},{"title":"card_267","front":"What are Dense Codes?","back":"A way to put symbols or words into a dictionary or array, and use the indices as the values in the text to save space so that words are not repeated.\n"},{"title":"card_268","front":"What is the LZ in LZ compression?","back":"Lempel-Ziv\n"},{"title":"card_269","front":"What is OS hardware virtualization?","back":"The abstraction of heterogeneous hardware provided by the operating system, to hide the details of interfacing with various hardware so that they share a common interface for that type.\n"},{"title":"card_270","front":"What is a process?","back":"An instance of an executing program consisting of an address space and one or more threads of control. It has restricted rights. It owns a region of memory. It owns file descriptors, file system context. It encapsulates one or more threads sharing the process' resources. It is isolated from other processes.\n"},{"title":"card_271","front":"What is a context switch?","back":"The copying out and in of register state to switch from running one process to running another.\n"},{"title":"card_272","front":"What is the scheduler?","back":"The scheduler manages the priorities of user and OS processes.\n"},{"title":"card_273","front":"What causes operating systems to crash most of the time?","back":"Device drivers. They are in the kernel and very low level. They have access to all the hardware, including memory. They are written by authors outside of the operating system.\n"},{"title":"card_274","front":"What is a process VM?","back":"A virtual environment that supports the execution of a single program. This is provided by an operating system.\n"},{"title":"card_275","front":"What is a system VM?","back":"A virtual environment that supports the execution of an entire operating system and its applications.\n"},{"title":"card_276","front":"How does the OS abstract the environment for a process?","back":"Each process thinks it has all the memory and CPU time, and thinks it owns all devices.\n"},{"title":"card_277","front":"What is fault isolation?","back":"Processes are unable to directly impact other processes. Bugs can't crash the whole machine.\n"},{"title":"card_278","front":"What is a thread?","back":"A single, unique execution context.\n"},{"title":"card_279","front":"What's the maximum address in memory for a 32 bit processor?","back":"2^32 - 1\n"},{"title":"card_280","front":"What is the execution sequence for a program?","back":"- Fetch instruction\n- Decode\n- Execute (perhaps using ALU and writing result to a register)\n- Write results to registers or memory\n- Increment program counter\n- Repeat\n"},{"title":"card_281","front":"What does the program counter point to?","back":"An address in memory that contains the current instruction.\n"},{"title":"card_282","front":"What is the stack pointer?","back":"A register that holds the address of the top of the stack portion of a process' memory.\n"},{"title":"card_283","front":"What is the heap pointer?","back":"A register that holds the address of the top of the heap portion of a process' memory.\n"},{"title":"card_284","front":"What is multiprogramming?","back":"Making one processor appear as multiple processors, each handling one process each.\n"},{"title":"card_285","front":"What triggers a context switch?","back":"Timer interrupt, hardware interrupt, I/O where we're waiting for a read or write to complete (OS doesn't want to waste time waiting), voluntary yield.\n"},{"title":"card_286","front":"What is dual-mode operation?","back":"Hardware provides at least 2 modes: user mode and kernel (aka: supervisor, protected) mode.\n"},{"title":"card_287","front":"How does the OS run a program?","back":"It does an exec from kernel mode (system mode 1). We go to system mode 0, user mode. When the program exits, we switch back to kernel mode.\n"},{"title":"card_288","front":"How does a user program interact with the kernel?","back":"It makes a system call, and the kernel takes over, completes the action, and the kernel returns to the process (back to user mode).\n"},{"title":"card_289","front":"What happens when the hardware needs something to happen?","back":"It does an interrupt, and the kernel takes control, switches the process, and once hardware task is complete, does a return from interrupt back to user mode.\n"},{"title":"card_290","front":"What happens when a program makes an exception?","back":"The program terminates, and switches to kernel mode.\n"},{"title":"card_291","front":"What is base and bound?","back":"It's a memory addressing restriction where a processes are only allowed access to the memory between a base address and the bound + base addresses. Each process has its own base and bound. A drawback is you don't get address 0. Address translation fixes this.\n"},{"title":"card_292","front":"How does the OS know how to handle an interrupt?","back":"It keeps an interrupt vector in the memory of the OS. Each interrupt type is mapped to an address to execute. They are just pointers to code in the OS.\n"},{"title":"card_293","front":"What is the difference between PC and uPC?","back":"PC is the program counter for the current process. uPC is the PC of the user process we will return to once an interrupt or other OS process switches context.\n"},{"title":"card_294","front":"How are base and bound enforced?","back":"They are stored in registers. Access is restricted by the hardware.\n"},{"title":"card_295","front":"How does x86 do segments and stacks?","back":"Each process' individual segments (heap, stack, code, static data) get their own base and bound. They don't even need to be adjacent in memory and their location is hidden by memory addressing.\n"},{"title":"card_296","front":"When a process forks, what happens?","back":"The process is paused, and a complete copy is made: code, stack, heap, data, program counter and registers.\nThe child and parent resume with returning from fork syscall.\n"},{"title":"card_297","front":"What does fork() return?","back":"It returns the child process id to the parent, and 0 to the child. < 0 if error.\n"},{"title":"card_298","front":"What does wait() do?","back":"Causes the parent process to pause until the child terminates.\n"},{"title":"card_299","front":"What does exec() do?","back":"It's a system call to change the currently running program to something else.\n"},{"title":"card_300","front":"What comes back from wait()?","back":"on success, returns the process ID of the terminated child; on error, -1 is returned.\n"},{"title":"card_301","front":"What is a signal?","back":"A system call to send a notification to another process.\n"},{"title":"card_302","front":"In a child process, what can you do with fork and then exec?","back":"Create a completely new process and then exit.\n"},{"title":"card_303","front":"What is a shell?","back":"A job control program. It allows a programmer to create and manage a set of programs to do some task.\n"},{"title":"card_304","front":"What is a microsecond? Also known as μs","back":"1 millionth of a second.\n"},{"title":"card_305","front":"What is a nanosecond?","back":"1 billionth of a second. ns\n"},{"title":"card_306","front":"What is a picosecond?","back":"A trillionth of a second.\n"},{"title":"card_307","front":"How does the kernel handle reads and writes?","back":"It buffers reads so they can be handled as a stream in your program. Writes are buffered and are not written until the kernel flushes the buffer.\n"},{"title":"card_308","front":"What's the difference between the fread, read, fwrite, write I/O calls?","back":"The ones with f are high-level I/O and streamed and buffered by the kernel. The non-f are low-level I/O.\n"},{"title":"card_309","front":"When a system call is made, where are parameters stored?","back":"In registers.\n"},{"title":"card_310","front":"What is a socket?","back":"It's an abstraction of a network I/O queue. It's a method of communication where a producer writes to one side, and a consumer reads from the other side. It's similar to writing and reading a file, but no file is involved.\n"},{"title":"card_311","front":"What sockets are in modern use?","back":"Local sockets to local machine, called UNIX sockets, and TCP/IP and UDP/IP.\n"},{"title":"card_312","front":"What is the GIL?","back":"It's the Global Interpreter Lock. It's is a part of CPython. It ensures only one thread runs in the interpreter at once. Having the GIL simplifies many low-level details (memory management, callouts to C extensions, etc.)\n"},{"title":"card_313","front":"When is the GIL released?","back":"During I/O (disk IO, network IO, output to display) including when a thread uses sleep.\n"},{"title":"card_314","front":"What is a \"tick\" in CPython?","back":"Approximately 1 machine instruction.\n"},{"title":"card_315","front":"What happens every 100 \"ticks\" in the CPython interpreter?","back":"A thread check occurs during which the thread releases the GIL then attempts to reacquire it. Other Python threads will contend for the the GIL. This is no longer the case in 3.4.\n"},{"title":"card_316","front":"What is a lock in CPython?","back":"It's a binary semaphore. It's not a mutex lock.\n"},{"title":"card_317","front":"What happens when the heap gets too large?","back":"It does a page fault, and the kernel will allocate more memory.\n"},{"title":"card_318","front":"What happens when the heap and stack meet in memory?","back":"A guard page is hit and the process is killed.\n"},{"title":"card_319","front":"Where is information about a process stored?","back":"In a PCB (process control block).\n"},{"title":"card_320","front":"Where is information about a thread stored?","back":"In a TCB (thread control block).\n"},{"title":"card_321","front":"What do multiple threads in the same process share?","back":"Heap, file descriptors, code, static data.\n"},{"title":"card_322","front":"What do threads in a process NOT share?","back":"Registers and stack.\n"},{"title":"card_323","front":"What can happen with thread stacks if one goes into a deep recursion?","back":"One thread's stack can grow into another thread's stack and write over it. A guard page can help to protect from that.\n"},{"title":"card_324","front":"What can cause a thread to give control back to the dispatcher?","back":"Thread returns control voluntarily (yield, requesting I/O (which blocks), wait for signal from another thread) or gets preempted by an interrupt.\n"},{"title":"card_325","front":"How long does it take to do a process context switch?","back":"3-4 microseconds.\n"},{"title":"card_326","front":"How long does it take to perform a thread context switch?","back":"100ns\n"},{"title":"card_327","front":"How often do context switches happen?","back":"Every 10-100 ms.\n"},{"title":"card_328","front":"Context switch time increases sharply with the size of what? (by 100x or more.)","back":"The working set - the subset of memory used by the process in a time window. Cache etc.\n"},{"title":"card_329","front":"What happens in a system call to get the OS to switch to kernel mode?","back":"A trap.\n"},{"title":"card_330","front":"How many threads should you run per process?","back":"One per core.\n"},{"title":"card_331","front":"How is concurrency accomplished?","back":"By multiplexing CPU time.\n"},{"title":"card_332","front":"What's the difference between parallelism and concurrency?","back":"Concurrency means running multiple blocks of instructions independently. Parallelism means running instructions at the same time, as on multiple cores at once.\n"},{"title":"card_333","front":"What is oversubscription?","back":"Spawning more threads than available cores.\n"},{"title":"card_334","front":"What is a race condition?","back":"When the outcome of a deterministic procedure becomes non-deterministic based on differences in subprocess timing.\n"},{"title":"card_335","front":"What can you put in place to exclusively use a resource without another process interfering?","back":"A mutex, or even better, a lock guard.\n"},{"title":"card_336","front":"How do you use a mutex in Python?","back":"import threading\n\nlock = threading.Lock()\n\n[first process]\nglobal lock\nlock.release()\n...\n[other process]\nglobal lock\nlock.acquire() // attempts to get access, waits if it can't\n"},{"title":"card_337","front":"What does a future do?","back":"Allows us to receive a return value from a function in a child thread.\n"},{"title":"card_338","front":"What is a promise?","back":"A promise to send a parameter to a child thread's function later.\n"},{"title":"card_339","front":"What is livelock?","back":"It occurs when multiple processes are attempting to deal with the current state, but neither makes progress. This can happen when a system is attempting to resolve a deadlock situation but another or the same process continue to trigger it.\nStarvation is another example.\n"},{"title":"card_340","front":"How long does a terminated process stay in the terminated state?","back":"Until the parent process does a wait to receive its exit code.\n"},{"title":"card_341","front":"In Python, what can you use to fork a process?","back":"The multiprocessing module. It supports process Pool and Process for making a pool of worker processes or forking temporary subprocesses.\n"},{"title":"card_342","front":"What does the concurrent.futures module offer?","back":"ThreadPoolExecutor\nProcessPoolExecutor\nExecutor objects\nFuture objects\n"},{"title":"card_343","front":"What is an interrupt?","back":"A hardware-invoked context switch. The interrupt handler always runs immediately.\n"},{"title":"card_344","front":"What happens during an interrupt?","back":"The currently running process' state is saved. We switch to kernel mode, the interrupt handler runs, and once its complete, the system goes back to user mode and the process continues.\n"},{"title":"card_345","front":"What really happens when you fork a process?","back":"A fork doesn't copy everything, it just duplicates the page table pointers, which are all set at read-only. Called copy-on-write. Once you write to memory, then it copies the state.\n"},{"title":"card_346","front":"What is multiprocessing?","back":"Parallel execution on multiple cores.\n"},{"title":"card_347","front":"What does a PCB contain?","back":"Everything about a process:\n- status\n- register state (when not in ready state)\n- PID, User, Executable, Priority\n- Execution time\n- Memory space, translation\n"},{"title":"card_348","front":"What is special about an interrupt handler?","back":"It disables interrupts and runs to completion.\n"},{"title":"card_349","front":"What are the five states a process can be in?","back":"- new (when being created)\n- ready\n- running\n- waiting (for I/O or event coordination)\n- terminated (waits for parent process to receive its exit code)\n"},{"title":"card_350","front":"What is the difference between filter() and map()?","back":"Filter uses a function that returns true or false (predicate).\nMap uses a function that returns a value.\n"},{"title":"card_351","front":"What is synchronization?","back":"Using atomic operations to ensure cooperation between threads.\n"},{"title":"card_352","front":"What is a critical section?","back":"A block of code that multiple threads within a process could try to access at the same time. To ensure correct processing, the critical section should be locked before entering, then unlocked when leaving. This creates a mutual exclusion on shared data.\n"},{"title":"card_353","front":"What is the priority inversion problem?","back":"A thread that is busy-waiting for a lock to be released ends up stealing CPU and getting a higher priority than the thread with the lock. SO since the waiting thread gets higher priority, the thread holding the lock can't complete and release the lock.\n"},{"title":"card_354","front":"What is busy-waiting?","back":"One or more threads is using a lot of CPU by continuously checking a value, or test&set() checking and writing a value in wiating for a lock to release, thus stealing CPU from the thread holding the lock.\n"},{"title":"card_355","front":"What is a semaphore?","back":"A semaphore limits access to a maximum number of threads (maximum concurrency) to have access to a source at the same time. It is commonly used to limit database connections.\n\nA semaphore (defined by Dijkstra) is kind of signaling solution for handling concurrency data integrity problems that arise in multi-threaded applications. It has a non-negative integer that supports 2 operations:\n- P() [proberen, to test/probe] - atomic operation that waits for semaphore to become > 1, then decrements it by 1 (wait)\n- V() [verhogen, to increment] - an atomic operation that increments the semaphore by 1, waking up any P (signal)\n\nThe initial semaphore value will determine how many threads can run in the critical section at once.\n"},{"title":"card_356","front":"What's another name for a mutual exclusion?","back":"Binary semaphore.\n"},{"title":"card_357","front":"What is a monitor?","back":"A lock and zero or more condition variables for managing concurrent access to shared data.\n"},{"title":"card_358","front":"What should locks and condition variables each be used for?","back":"locks - mutual exclusion\ncondition variables - scheduling constraints\n"},{"title":"card_359","front":"What is a condition variable?","back":"A queue of threads waiting for access to something in a critical section.\n"},{"title":"card_360","front":"What is a special feature of condition variables?","back":"It allows sleeping inside a critical section by atomically releasing lock at the time we sleep.\n"},{"title":"card_361","front":"What are the 3 methods on a condition variable?","back":"wait(&lock)\nsignal() - signals the next waiting member\nbroadcast() - signals all waiting members\n"},{"title":"card_362","front":"What type of scheduling do most modern processors use?","back":"Mesa-scheduling.\n"},{"title":"card_363","front":"What are some things the scheduler tries to accomplish?","back":"- minimize response time\n- maximize throughput\n- fairness\n"},{"title":"card_364","front":"What is a drawback of context switching?","back":"CPU cache misses as thread comes back from switching and finds the CPU cache doesn't have the values it had before.\n"},{"title":"card_365","front":"What's the convoy effect?","back":"Short processes get stuck behind long processes in a FIFO style ready queue.\n"},{"title":"card_366","front":"What is the round robin scheduling scheme?","back":"Each process gets a time quantum q milliseconds to run. 10-100ms, the q is tunable. Each process runs for that time slice (or until completion if close to done) and then goes back on the ready queue.\n"},{"title":"card_367","front":"What are pros of the round-robin scheduling scheme?","back":"- better for short jobs (they fit in the time slice)\n- fair\n"},{"title":"card_368","front":"What is a con of the round-robin scheduling scheme?","back":"Long jobs take longer because context-switching time adds up.\n"},{"title":"card_369","front":"How long does context switching take?","back":"0.1ms - 1ms\nIt's roughly 1% overhead.\n"},{"title":"card_370","front":"What is starvation?","back":"When low-priority jobs never get run because there are always higher priority jobs running.\n"},{"title":"card_371","front":"How does a process' priority get changed?","back":"The scheduler utilizes heuristics on interactivity, locking, burst behavior, etc.\n"},{"title":"card_372","front":"What are some methods of avoiding deadlock?","back":"- don't allow waiting for a resource (means a lot of retries)\n- make all threads request everything they'll need at the beginning\n- force all threads to request resources in a particular order preventing any cyclic uses of resources (so no cycle exists)\n- temporarily expand resources when a deadlock is detected\n"},{"title":"card_373","front":"What is the banker's algorithm for preventing deadlock?","back":"- allocate resources dynamically\n- evaluate each request and grant if some ordering of threads is still deadlock-free afterward\n- do so by pretending the request was granted, then running a simulation to see if a deadlock would occur\n"},{"title":"card_374","front":"How does the banker's algorithm solve the dining lawyers problem?","back":"When you try to grab a chopstick, it's either:\n- not the last chopstick\n- is last chopstick but someone else will have two afterwards\n"},{"title":"card_375","front":"Does the CPU use virtual addresses or physical addresses?","back":"Virtual addresses\n"},{"title":"card_376","front":"What translates virtual to physical addresses?","back":"The MMU - the memory management unit\n"},{"title":"card_377","front":"What are the four conditions needed for a deadlock?","back":"- mutual exclusion\n- hold and wait\n- no preemption\n- circular wait\n"},{"title":"card_378","front":"How many bits represent an IPv4 address?","back":"32\n"},{"title":"card_379","front":"How many bits represent an IPv6 address?","back":"128\n"},{"title":"card_380","front":"Name some of the protocols used within the TCP/IP application layer.","back":"- http\n- https\n- ftp\n- tftp\n- ntp\n- irc\n- telnet\n- smtp\n- ssh\n- dns\n- snmp\n- pop3\n"},{"title":"card_381","front":"What is NTP?","back":"Network time protocol\n"},{"title":"card_382","front":"What are some protocols in the TCP/IP transport layer?","back":"- TCP\n- UDP\n"},{"title":"card_383","front":"What are some TCP/IP network layer protocols?","back":"IP - internet protocol\nICMP - internet control message protocol\nARP - address resolution protocol\n"},{"title":"card_384","front":"What are some TCP/IP network access layer protocols?","back":"- RJ45\n- ISDN\n- Microwave\n- Ethernet\n- Wifi\n- Fiber optics\n- ATM\n- RJ48\n- Copper cables\n"},{"title":"card_385","front":"What is a PDU?","back":"Protocol data unit\n- generic term used to describe the information at a given layer in the TCP/IP stack\n"},{"title":"card_386","front":"What is the PDU for OSI layer 7?","back":"data, determined by what information is being exchanged: text, encrypted text, compressed data\n"},{"title":"card_387","front":"What are the PDUs for the the OSI transport layer?","back":"for TCP, it's called a segment\nfor UDP, it's called a datagram\n"},{"title":"card_388","front":"What is the PDU for the TCP/IP internet layer?","back":"packet\n"},{"title":"card_389","front":"What are the 2 PDUs of the OSI Network Access layer?","back":"data link layer: frames\nphysical layer: bits\n"},{"title":"card_390","front":"What is the port for DNS?","back":"53\n"},{"title":"card_391","front":"What is the port for telnet?","back":"23\n"},{"title":"card_392","front":"What is the port for ssh?","back":"22\n"},{"title":"card_393","front":"What is the port range for clients?","back":"8000-65535\n"},{"title":"card_394","front":"How many bits are in an ethernet frame?","back":"48 bits, represented as a hexadecimal number.\n"},{"title":"card_395","front":"What does MAC stand for?","back":"medium access control, a sublayer in the data link layer.\n"},{"title":"card_396","front":"What is the PDU and the addressing at the data link layer?","back":"PDU: frame\nAddressing: physical (MAC) address\n"},{"title":"card_397","front":"What devices are at the data link layer?","back":"Bridges, switches (multi-port bridge). They inspect frames and forward or not.\n"},{"title":"card_398","front":"What devices are at the Internet/Network layer?","back":"Routers\nLayer 3 switches: can be a switch or a router\n"},{"title":"card_399","front":"What is the PDU and the addressing at the Internet/Network layer?","back":"PDU: packet\nAddressing IP address\n"},{"title":"card_400","front":"What is the PDU and the addressing at the Transport layer?","back":"PDU: segment\naddressing: ports\n"},{"title":"card_401","front":"What devices are at the Transport layer?","back":"Firewalls\n"},{"title":"card_402","front":"What is a socket in HTTP?","back":"The combination of an IP address and a port.\n"},{"title":"card_403","front":"What is involved in the 3 way handshake (TCP)?","back":"SYN=1 - synchronize, gives a Seq number and expects that number + 1 in response\nACK=1 - sent by acknowledging server with incremented number, who also sends a SYN=1 and a Seq\nSYN=0 ACK=1 and the Seq (incremented number) back to the server\n\nNow you're talking!\n"},{"title":"card_404","front":"Does Kerberos use symmetric or asymmetric encryption?","back":"Symmetric. It tracks all principals and their keys in its KDC table.\n"},{"title":"card_405","front":"What are the 7 layers of the OSI model?","back":"- application\n- presentation\n- session\n- transport\n- network\n- data link\n- physical\n"},{"title":"card_406","front":"What are the 4 layers of TCP/IP?","back":"- application (application, presentation, session in OSI)\n- transport\n- internet (network in OSI)\n- network access (data link & physical in OSI)\n"},{"title":"card_407","front":"How is an SSL certificate generated by the certificate authority (CA)?","back":"The common name and public key for a given domain name, signed by the certificate authority's secret key.\nThe browser can verify the cert with CA's public key.\n"},{"title":"card_408","front":"What is the secure flag on a cookie?","back":"When set on a cookie, it will only be sent on https requests.\nWhen not set, cookie will be sent on both http and https requests.\n"},{"title":"card_409","front":"When does a Python multi-threaded program terminate?","back":"The entire Python program exits when no alive non-daemon threads are left.\n"},{"title":"card_410","front":"In Python, if a thread is set to daemon, what happens when the thread sleeps?","back":"If the Python program reaches its end, the thread will be killed even if it's sleeping.\n"},{"title":"card_411","front":"If a thread is a daemon, what happens when you do a join()?","back":"The main thread will wait for it.\n"},{"title":"card_412","front":"What does WebRTC stand for?","back":"Web Real-Time Communication\n"},{"title":"card_413","front":"Give an example of the thread-per-connection pattern.","back":"A web server might spawn a thread per connection, then reuse that thread once the connection ends, or terminate the thread.\n"},{"title":"card_414","front":"Give an example of the thread pool model.","back":"A pool of threads can be maintained in order to quickly provide one as a resource for a database connection.\n"},{"title":"card_415","front":"What is contained in a packet?","back":"- source IP\n- destination IP\n- data - some portion of the final payload\n"},{"title":"card_416","front":"What is TLS?","back":"The successor to SSL. All of SSL's versions have been deprecated due to security issues.\n"},{"title":"card_417","front":"What is the purpose of the transport layer?","back":"To allow multiple applications to use one network connection simultaneously.\n"},{"title":"card_418","front":"What is DNS spoofing?","back":"A DNS server is compromised and returns incorrect IP addresses for a some domains.\n"},{"title":"card_419","front":"What does TCP stand for?","back":"Transmission Control Protocol\n"},{"title":"card_420","front":"What is special about TCP?","back":"It manages the sending and receiving of packet data.\nIt acknowledges receipt of packets.\nIf packets are missing, the source will resend the missing packets.\n"},{"title":"card_421","front":"What is HTTP?","back":"The protocol for client-server communication.\n"},{"title":"card_422","front":"What does UDP stand for?","back":"User Datagram Protocol.\n"},{"title":"card_423","front":"What is the size of a UDP header?","back":"8 bytes\n"},{"title":"card_424","front":"What is the size of a TCP header?","back":"20 bytes\n"},{"title":"card_425","front":"What does ICMP stand for?","back":"Internet Control Messaging Protocol\n"},{"title":"card_426","front":"What does ICMP allow you to do?","back":"Allows devices to communicate and send errors. Can echo to see if a device is on the network.\n"},{"title":"card_427","front":"What does SNMP stand for?","back":"Simple Network Management Protocol.\n"},{"title":"card_428","front":"What does SNMP do?","back":"Gathers info from machines on the network when each box has an SNMP agent installed. Can send a large amount of info about machines, software installed, and machine configuration.\n"},{"title":"card_429","front":"Do you need to establish a connection before sending data via UDP?","back":"No, it's connectionless.\n"},{"title":"card_430","front":"Tell me about the checksum in a UDP packet.","back":"It's a 16-bit checksum. It's only mandatory on IPv6\n"},{"title":"card_431","front":"How many times are packets sent in UDP?","back":"Once.\n"},{"title":"card_432","front":"What is special about UDP?","back":"It's connectionless, packets are only sent once and not re-sent if dropped. Packets may not arrive in the right order, and there is no ordering mechanism to fix on the receiving end. No congestion control.\n"},{"title":"card_433","front":"What's special about TCP?","back":"It does a 3-way handshake before data is sent.\nDelivery is acknowledged by receiver.\nPackets missing within a certain time window are re-requested.\nPackets are put in order on receipt.\nCongestion control: can delay delivery until network is uncongested.\nIPv4 and IPv6: error detection, checksum mandatory.\n"},{"title":"card_434","front":"What does OSI stand for?","back":"Open Systems Interconnect\n"},{"title":"card_435","front":"Why was OSI created?","back":"To solve the interoperability problem of having multiple heterogeneous networks.\n"},{"title":"card_436","front":"Is OSI just a model?","back":"Yes.\n"},{"title":"card_437","front":"What network protocol won the networking wars?","back":"TCP/IP, based on the OSI model.\n"},{"title":"card_438","front":"What happens at the Application level of the OSI model?","back":"This is where applications live and they handle data in many forms.\n"},{"title":"card_439","front":"What happens in the Session layer of the OSI model?","back":"This layer handles configuration of the data:\n- encryption\n- compression\n- translation to and from different character encodings\n"},{"title":"card_440","front":"What happens at the Session layer of the OSI model?","back":"This layer controls the communication's access via:\n- login rights\n- permissions\n- rights\n- roles\n"},{"title":"card_441","front":"What happens at the Transport layer of the OSI model?","back":"This layer guarantees end-to-end delivery of data:\n- packet ordering\n- error detection\n- acknowledgements\n"},{"title":"card_442","front":"What happens at the Network layer of the OSI model?","back":"This layer's function is to find the shortest path through the network to the destination network.\nDeals with congestion, bandwidth, etc.\n"},{"title":"card_443","front":"What happens at the Data Link layer of the OSI model?","back":"It decides whose turn it is to talk on the network using bus arbitration methods.\nIt finds the physical device on the network.\n"},{"title":"card_444","front":"What happens at the Physical layer of the OSI model?","back":"It's the physical network that deals with the physical transmission of electricity through wire:\n- cables\n- voltages\n- frequencies\n- connectors\n- bits\n- transfer rates\n- and much more\n"},{"title":"card_445","front":"How does HTTP/2 save bandwidth?","back":"Headers are compressed and do not need to send the same headers in a session if they haven't changed.\nServers can send assets referenced in a document without waiting for discrete requests for them.\n"},{"title":"card_446","front":"How does HTTP/2 improve cache breaking?","back":"A server can send updated assets using server push when it recognizes a file has changed.\n"},{"title":"card_447","front":"What is the stream parallelism in HTTP/2?","back":"It's fully multiplexed, so it can use 100-1000 streams in a connection.\n"},{"title":"card_448","front":"Is HTTP/2 binary or textual?","back":"HTTP/2 is a binary protocol.\n"},{"title":"card_449","front":"How are headers and body treated differently in HTTP/2?","back":"They are split into a header frame and a data frame. Multiple requests can be interleaved in a connection, so a request doesn't block.\n"},{"title":"card_450","front":"What is priority in HTTP/2?","back":"Different assets can have different priority so that below the fold content can arrive later.\n"},{"title":"card_451","front":"What is the range of the first octet on a Class A network?","back":"1-126. We don't use 0 or 127.\n"},{"title":"card_452","front":"How many network IDs are there on a Class A network?","back":"2^7 = 128\nFirst bit is 0, bits 1-7 are network IDs\n"},{"title":"card_453","front":"How many host IDs are supported on a Class A network?","back":"2^24 = 16 million\nThere are 8 bits for the network ID, and the remaining 24 bits are for host IDs.\nSo there are 16 million per network.\n"},{"title":"card_454","front":"What is the range of the first octet on a Class B network?","back":"128 - 191\n"},{"title":"card_455","front":"How many network IDs are supported on a Class B network?","back":"2^14 = 16,384\nFirst 2 bits are 10, bits 3-16 are network IDs\n"},{"title":"card_456","front":"How many host IDs are supported on a Class B network?","back":"2^16 = 65,536\nSo there are 65,536 per network\n"},{"title":"card_457","front":"What is the range of the first octet on a Class C network?","back":"192-223\n"},{"title":"card_458","front":"How many network IDs are supported on a Class C network?","back":"2^21 = 2 million\nFirst 3 bits are 110, bits 4-24 are network IDs\n"},{"title":"card_459","front":"How many host IDs are supported on a Class C network?","back":"2^8 = 256\nThere are 256 hosts per network\n"},{"title":"card_460","front":"What is a class D network reserved for?","back":"Multicasting\n"},{"title":"card_461","front":"What is unicasting?","back":"Sending a packet from one host to another.\n"},{"title":"card_462","front":"What does a network ID end in?","back":"0\n"},{"title":"card_463","front":"What does a broadcast ID end in?","back":"255\n"},{"title":"card_464","front":"Who does a broadcast address of 255.255.255.255 send to?","back":"All hosts within the network.\n"},{"title":"card_465","front":"What is a directed broadcast?","back":"It's a broadcast to all hosts within another network.\n"},{"title":"card_466","front":"What is a limited broadcast address?","back":"The limited broadcast address is the address formed by setting all 32 bits of the IP address to 1 (255.255.255.255). The limited broadcast address is used when an IP node must perform a one-to-everyone delivery on the local network but the network ID is unknown.\n"},{"title":"card_467","front":"Why should you make networks as small as possible?","back":"For:\n- security\n- maintenance\n- management\n"},{"title":"card_468","front":"How you divide a network?","back":"By subnetting.\n"},{"title":"card_469","front":"What does a /27 CIDR mean?","back":"The first 27 bits are masked with 1s. The remaining 5 bits are reachable in the subnet.\n"},{"title":"card_470","front":"What does a /24 CIDR mean?","back":"The first 24 bits of the IP address are masked. Only hosts with addresses in the unmasked portion are reachable.\n"},{"title":"card_471","front":"What is a block cipher?","back":"A block cipher is a method of encrypting text (to produce ciphertext) in which a cryptographic key and algorithm are applied to a block of data (for example, 64 contiguous bits) at once as a group rather than to one bit at a time.\n"},{"title":"card_472","front":"What is QUIC?","back":"QUIC is a new transport which reduces latency compared to that of TCP. On the surface, QUIC is very similar to TCP+TLS+HTTP/2 implemented on UDP.\n"},{"title":"card_473","front":"What is Capsicum?","back":"A sandboxing framework that adds capability-based security to unix-like kernels and denies access to global namespaces.\n"},{"title":"card_474","front":"What is a global namespace in unixy terms?","back":"aspects of a system that can be accessed from anywhere:\n- file paths\n- networks\n- PIDs\n"},{"title":"card_475","front":"What is Google Native Client?","back":"Also called NaCl, Native Client is a sandbox for running compiled C and C++ code in the browser efficiently and securely, independent of the user’s operating system.\n"},{"title":"card_476","front":"What are web sockets?","back":"Full-duplex communication between client and server.\n"},{"title":"card_477","front":"What is the same-origin policy?","back":"Goal: Two websites should not be able to tamper with each other.\nStrategy: each resource is assigned an origin. JS can only access resources from its own origin.\nOrigin: scheme + hostname + port\n"},{"title":"card_478","front":"How can 2 origins (let's say 2 frames) communicate?","back":"window.postMessage (HTML5) allows for sending data messages between two windows/frames across domains.\n"},{"title":"card_479","front":"What is JIT compilation?","back":"JIT compilation, also known as dynamic translation, is compilation done at run-time rather than ahead of time (AOT).\n"},{"title":"card_480","front":"What is PyPy?","back":"PyPy is a replacement for CPython. It is built using the RPython language that was co-developed with it. RPython is a subset of Python and can be translated to C. The main reason to use it instead of CPython is speed: it runs generally faster due to JIT compilation.\nPyPy implements Python 2.7.10. It supports all of the core language, passing the Python test suite (with minor modifications that were already accepted in the main python in newer versions). It supports most of the commonly used Python standard library modules.\n"},{"title":"card_481","front":"What does SMT stand for?","back":"Satisfiability modulo theories.\n"},{"title":"card_482","front":"What is an SMT solver?","back":"A satisfiability modulo theories solver solves for large interconnected logic formulas to determine if a given formula can be satisfied. These are helpful for determining the outcome or inputs for a program using symbolic execution.\n"},{"title":"card_483","front":"How do we find that a condition exists that will cause a program to have a predicted outcome?","back":"Using an SAT solver (using logic tests) and an SMT solver (that plugs in numbers), and tells the SAT solver where it got it wrong. They provide feedback in a cycle to each other until a condition can be found.\n"},{"title":"card_484","front":"What is transactional memory?","back":"Transactional memory attempts to simplify concurrent programming by allowing a group of load and store instructions to execute in an atomic way. It is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing.\n"},{"title":"card_485","front":"What is software transactional memory?","back":"Software transactional memory provides transactional memory semantics in a software runtime library or the programming language, and requires minimal hardware support (typically an atomic compare and swap operation, or equivalent). As the downside, software implementations usually come with a performance penalty, when compared to hardware solutions.\n"},{"title":"card_486","front":"Does PyPY have a GIL?","back":"Yes. The GIL is very difficult to remove. You can use pypy-stm instead, which uses software transactional memory, but will suffer a performance penalty.\n"},{"title":"card_487","front":"How can a server deal with a SYN flood attack?","back":"When it detects a large number of SYN packets at once, or the size of its SN (sequence number) data structure reaches a certain threshold of entries, it can switch to a stateless version, where it send SN responses as signed values with a timestamp, and if it receives one back it lets them through without needing a lookup table.\n"},{"title":"card_488","front":"What is a stack canary?","back":"It's a buffer overflow defense where a random value is pushed onto the stack after the saved EBP, and before tearing down the stack frame, the value is checked. Any buffer flow targeting the return instruction pointer would have to have overwritten this value.\n"},{"title":"card_489","front":"What type of buffer overflow protection does gcc and Visual Studio employ?","back":"They use a stack check guard of bytes before and after the buffer's allocated memory. Once values are written to the buffer, the bytes are checked to ensure they are still the same.\n"},{"title":"card_490","front":"What is scalability?","back":"Scalability is the measure to which a system can adapt to a change in demand for resources, without negatively impacting performance.\n"},{"title":"card_491","front":"What is Akka?","back":"An open source project that provides a simpler, single programming model - one way of coding for concurrent and distributed applications - the actor programming model.\nAkka’s primary goal is to make it simpler to build applications that are deployed in the cloud or run on devices with many cores and that efficiently leverage the full capacity of the computing power available. It’s a toolkit that provides an actor model, runtime, and required supporting tools for building scalable applications.\n"},{"title":"card_492","front":"What is an actor?","back":"Briefly, actors are a lot like message queues without the configuration and message broker installation overhead. They’re like programmable message queues shrunk to microsize—you can easily create thousands, even millions of them. They don’t “do”\nanything unless they’re sent a message.\nMessages are simple data structures that can’t be changed after they’ve been created, or in a single word, they’re immutable.\nActors can receive messages one at a time and execute some behavior whenever a message is received. Unlike queues, they can also send messages (to other actors).\nEverything an actor does is executed asynchronously. Simply put, you can send a message to an actor without waiting for a response. Actors aren’t like threads, but messages sent to them are pushed through on a thread at some point in time. How actors are connected to threads is configurable - this is not a hardwired relationship.\nFor now the most important aspect of actors is that you build applications by sending and receiving messages. A message could be processed locally on some available thread, or remotely on another server. Exactly where the message is processed and where the actor lives are things you can decide later, which is very different compared to hardcoding threads and RPC style networking. Actors make it easy to build your application out of small parts that resemble networked services, only shrunk to microsize in footprint and administrative overhead.\n"},{"title":"card_493","front":"What is an IDL-based encoding?","back":"An interface description language or interface definition language (IDL) encoding. \nIt requires a schema definitions. They offer peace of mind with respect to data format and validation for consumers while sacrificing flexibility in the schema’s evolution.\n"},{"title":"card_494","front":"What is Tarantool?","back":"An in-memory noSQL database that uses write-ahead logging for crash resistance and persistence.\n"},{"title":"card_495","front":"What is a coroutine?","back":"An object representing activity that eventually completes. Also refers the the function we call that returns a coroutine.\nIn Python, coroutines are generators.\n"},{"title":"card_496","front":"What is a future?","back":"An object representing a result that may not be available yet.\n"},{"title":"card_497","front":"What is AQP?","back":"Approximate query processing. It means pulling a sample of data instead of taking time to process an exact result. It is often used when a data storage involves terabytes or more.\n"},{"title":"card_498","front":"How would you visualize billions of items in a graph?","back":"In many cases, you don't need to graph every point, just use visualization-aware sampling. Sometime 1% or less will do.\n"},{"title":"card_499","front":"What is F1/Spanner?","back":"Fault-Tolerant Distributed RDBMS (Spanner) Supporting Google's Ad Business (F1)\n"},{"title":"card_500","front":"What is Photon?","back":"Fault-tolerant and Scalable Joining of Continuous Data Streams\n"},{"title":"card_501","front":"What is Mesa?","back":"Geo-Replicated, Near Real-Time, Scalable Data Warehousing\n"},{"title":"card_502","front":"How does Google use multi-homed datacenters?","back":"A multi-homed system runs live in multiple datacenters all the time. Each datacenter processes work all the time, and work is dynamically shared between datacenters to balance load. When one datacenter is slow, some fraction of work automatically moves to faster datacenters. When a datacenter is completely unavailable, all its work is automatically distributed to other datacenters.\n"},{"title":"card_503","front":"What is ElasticSearch?","back":"Open Source, Distributed, RESTful Search Engine\n"},{"title":"card_504","front":"What is an example of a circuit breaker?","back":"Start sending 503s if your service is choked to avoid numerous simultaneous retries that just make the system worse.\n"},{"title":"card_505","front":"What is the name of Google's search ranking algorithm?","back":"Hummingbird. PageRank is just one factor used by the algorithm.\n"},{"title":"card_506","front":"What is celery?","back":"Distributed Task Queue\n"},{"title":"card_507","front":"LRU is the most popular type of what kind of policy?","back":"Eviction\n"},{"title":"card_508","front":"What does an eviction policy try to predict?","back":"An eviction policy tries to predict which entries are most likely to be used again in the near future, thereby maximizing the hit ratio\n"},{"title":"card_509","front":"What is Caffiene?","back":"Caffeine is a high performance, near optimal caching library based on Java 8.\n"},{"title":"card_510","front":"What is request coalescing?","back":"When many requests arrive for some content that’s missing in the cache (cache miss), only one instance request will proceed to the backend to fetch the content on behalf of all to avoid a flood.\n"},{"title":"card_511","front":"When might you need to use a NoSQL database","back":"You don’t have any relational data.\nIf you need to store > 5 TB of data or you have an incredibly data intensive workload.\nYour application has super low-latency requirements.\nYou need really high throughput.\n"},{"title":"card_512","front":"What is AMP?","back":"AMP is a restricted subset of HTML designed to make the web fast on mobile devices.\nProvides a shared library of scripts so they don’t have to downloaded every time.\nSets standards for the architecture of advertising so advertising doesn't infect pages.\nShared mechanism for collecting data for analytics so you don’t have N different packages on a page gathering stats.\n"},{"title":"card_513","front":"What is a benefit of making processes asynchronous?","back":"Flexibility in the architecture. Getting users on hooked on synchronous low-latency interactions doesn't allow for architecture flexibility.\n"},{"title":"card_514","front":"What is BASE?","back":"basically available\nsoft state\neventually consistent\n\nA BASE based system is more tolerant to latency because it is an inherently partitioned and loosely coupled architecture and it uses eventual consistency.\n"},{"title":"card_515","front":"What is ACID?","back":"atomicity\nconsistency\nisolation\ndurability\n"},{"title":"card_516","front":"What is the CAP theorem?","back":"The CAP theorem, also named Brewer's theorem, states that it is impossible for a distributed computer system to simultaneously provide all three of the following guarantees:\n\n- Consistency (all nodes see the same data at the same time)\n- Availability (every request receives a response about whether it succeeded or failed)\n- Partition tolerance (the system continues to operate despite arbitrary partitioning due to network failures)\n"},{"title":"card_517","front":"What is zero copy?","back":"Applications that use zero copy request that the kernel copy the data directly from the disk file to the socket, without going through the application. Zero copy greatly improves application performance and reduces the number of context switches between kernel and user mode.\n"},{"title":"card_518","front":"What is a metaclass?","back":"Any callable (function or class) that implements type()'s function signature.\n"},{"title":"card_519","front":"What is privilege separation?","back":"Separating an application into different areas so a vulnerability in one area doesn't affect the entire application.\n"},{"title":"card_520","front":"In security, what is a principal?","back":"An entity with privileges or rights.\n"},{"title":"card_521","front":"In Unix, who is the owner of a file?","back":"The user with the user ID that matches the UID of the inode.\n"},{"title":"card_522","front":"What privilege do you need to lookup files or directories in a path?","back":"The executable permission.\n"},{"title":"card_523","front":"When is security enforced on a file?","back":"Security is checked when the file descriptor is created. Then it's up to the user to be careful and secure the file descriptor.\n"},{"title":"card_524","front":"What is ptrace?","back":"ptrace is a system call found in several Unix and Unix-like operating systems. By using ptrace, one process can control another, enabling the controller to inspect and manipulate the internal state of its target.\n"},{"title":"card_525","front":"What can you use to debug a process?","back":"ptrace\n"},{"title":"card_526","front":"What user privilege is required to bind to ports < 1024?","back":"root\n"},{"title":"card_527","front":"During system bootstrapping, what call is performed by the system to give a non-root user the ownership of a process?","back":"setuid()\n"},{"title":"card_528","front":"What are the setuid binaries?","back":"su\nsudo\n"},{"title":"card_529","front":"What does chroot do?","back":"Changes the root directory (/) for a user to be a directory on the filesystem where they can't escape.\n"},{"title":"card_530","front":"What is a confused deputy?","back":"A confused deputy is a computer program that is innocently fooled by some other party into misusing its authority. It is a specific type of privilege escalation. In information security, the confused deputy problem is often cited as an example of why capability-based security is important, as capability systems protect against this whereas access control list-based systems do not.\nThe classic example is a Fortran compiler that creates a billing record for each use. A user was able to tell the compiler to output a binary with the same name as the billing file, overwriting it.\n"},{"title":"card_531","front":"What is an example of a confused deputy in the web frontend world?","back":"A CSRF attack.\n"},{"title":"card_532","front":"What is ambient authority, or ambient privilege?","back":"The decision about whether a process or agent can perform an action is based on information not explicitly stated, but inherited instead.\n"},{"title":"card_533","front":"What is a capability?","back":"The privilege to act upon something given your ownership of it, and the inability to act on something using an intermediate process' privileges. An example would be a function where you pass a file descriptor as an argument and the function uses your capability, not its own.\n"},{"title":"card_534","front":"What is a requirement of enabling sandboxing?","back":"The kernel must be able to support it by disallowing system calls that reference global namespaces:\n- file paths starting at root - must be relative\n- network\n- PIDs - use process descriptors instead\n"},{"title":"card_535","front":"How is RSA decryption optimized for speed?","back":"- c^d mod p and c^d mod q are processed in parallel and merged at the end using the Chinese remainder theorem\n- put into Montgomery format\n- sliding windows to exponentiate on bits of exponent\n- perhaps a single extra reduction\n- convert back from Montgomery format\n- merge using CRT\n"},{"title":"card_536","front":"How do you change a positive integer to negative?","back":"Subtract 1, flip all bits\n"},{"title":"card_537","front":"How do you change a negative integer to positive?","back":"Flip all bits, then add 1\n"},{"title":"card_538","front":"What is Intel architecture?","back":"CISC - Complex Instruction Set Computer\nMany special-purpose instructions.\n"},{"title":"card_539","front":"What size are Intel instructions?","back":"They are variable-length, from 1 to theoretically 16 bytes.\n"},{"title":"card_540","front":"What is RISC?","back":"Reduced Instruction Set Architecture. \n- more registers\n- fewer, fixed-sized instructions\n- used in PowerPC, ARM, SPARC, MIPS\n"},{"title":"card_541","front":"What Endianness is Intel?","back":"Little Endian, but only in memory. In registers, all are Big Endian.\n"},{"title":"card_542","front":"What is Little Endianness?","back":"The least significant bytes of a word or larger are stored in the lowest address. All bytes are the same. There is no Endianness within a byte.\n"},{"title":"card_543","front":"How many registers are on CISC?","back":"8 general-purpose registers and an instruction pointer. 2 of 8 are not that general.\n"},{"title":"card_544","front":"What is the word size on Intel?","back":"16 bits\n"},{"title":"card_545","front":"What is the double-word size on Intel?","back":"32 bits\n"},{"title":"card_546","front":"What is Big Endianness?","back":"The most significant bytes of a word or larger are stored in the lowest address.\n"},{"title":"card_547","front":"What is the EAX register used for?","back":"Stores the function's return value.\n"},{"title":"card_548","front":"What is the EBX register used for?","back":"Base pointer to the data section.\n"},{"title":"card_549","front":"What is the ECX register used for?","back":"Counter for string and loop operations.\n"},{"title":"card_550","front":"What is the EDX register used for?","back":"I/O pointer\n"},{"title":"card_551","front":"What is the ESI register used for?","back":"Source pointer for string or other copy operations.\n"},{"title":"card_552","front":"What is the EDI register used for?","back":"Destination pointer for string or other copy operations.\n"},{"title":"card_553","front":"What is the ESP register used for?","back":"Stack pointer\n"},{"title":"card_554","front":"What is the EBP register used for?","back":"Stack frame base pointer\n"},{"title":"card_555","front":"What is the EIP register used for?","back":"Instruction pointer - next instruction pointer to execute.\n"},{"title":"card_556","front":"What are the caller-save registers?","back":"eax\nedx\necx\n"},{"title":"card_557","front":"What are the callee-save registers?","back":"ebp\nebx\nesi\nedi\n"},{"title":"card_558","front":"Other than the main registers, what other registers can be used?","back":"Legacy 8 and 16-bit registers: AX, AH, AL, SP, BP, SI\n"},{"title":"card_559","front":"What is the caller register-saving convention on Linux systems?","back":"cdecl - C declaration\n"},{"title":"card_560","front":"What is avalancing?","back":"The effect of a hashing method where a small change in the input has a large effect on the output.\n"},{"title":"card_561","front":"What is Chef?","back":"A configuration tool. You write or reuse recipes that declare the state you wish your server to be in. It calculates the delta and builds out for you.\n"},{"title":"card_562","front":"What is an example of a non-cryptographic hash function?","back":"MurmurHash is an efficient, non-cryptographic hash function suitable for general hash-based lookup. The name comes from two basic operations, multiply (MU) and rotate (R), used in its inner loop. It has an avalanche effect. The current version is MurmurHash3 which yields a 32-bit or 128-bit hash value.\n"},{"title":"card_563","front":"How could you process calculations on elements of an array in parallel?","back":"Using recursion, divide and conquer, breaking down the array into smaller segments, then merging the values as the recursion unwinds. Non-mutation of the array means locking is not required.\n"},{"title":"card_564","front":"What factor should you keep in mind when doing parallel computation on different parts of a large data structure?","back":"The memory bandwidth of your RAM. It can become a bottleneck.\n"},{"title":"card_565","front":"What will be the computation time when processing multiple tasks?","back":"The length of time the longest subcomputation takes.\n"},{"title":"card_566","front":"Why should you avoid starting and joining a task or thread on the same line or proximity?","back":"Execution on the current thread will block until it completes, thereby obviating the concurrent call.\n"},{"title":"card_567","front":"What factors affect performance?","back":"- processor speed \n- number of processors\n- memory access latency and throughput\n- cache behavior\n- runtime behavior (garbage collection, JIT compilation, thread scheduling)\n"},{"title":"card_568","front":"What is Amdahl's Law?","back":"It gives the theoretical speedup in latency of the execution of a task at fixed workload that can be expected of a system whose resources are improved.\n"},{"title":"card_569","front":"What aspects are important in measuring and benchmarking performance, parallel or otherwise?","back":"- multiple repetitions\n- statistical treatment - mean and variance\n- eliminate statistical outliers\n- ensuring steady-state (warm-up)\n- preventing anomalies (garbage collection, JIT compilation, compiler optimizations in benchmark code that misrepresents real-world)\n"},{"title":"card_570","front":"When associative operations are used, what does it mean?","back":"Grouping doesn't matter. It will evaluate to the same result.\n"},{"title":"card_571","front":"What is a synonym of reduce()?","back":"fold()\n"},{"title":"card_572","front":"What is the commutative property?","back":"The condition that a group of quantities connected by operators gives the same result whatever the order of the quantities involved. So order of operands doesn't matter, but grouping may matter.\n"},{"title":"card_573","front":"What is a bag?","back":"A multiset.\n"},{"title":"card_574","front":"What is a multiset?","back":"A set in which elements do not have to be unique.\n"},{"title":"card_575","front":"What are some examples of operations that are both associative and commutative?","back":"- Addition and multiplication of integers\n- Union, intersection, and symmetric difference of sets\n- Addition of vectors\n- Addition of matrices of fixed dimension\n- Addition and multiplication of polynomials\n"},{"title":"card_576","front":"What are some examples of operations that are associative but not commutative?","back":"- concatenation of lists\n- concatenation of strings\n- matrix multiplication\n"},{"title":"card_577","front":"What should we worry about floating point addition and multiplication?","back":"It is commutative but not associative.\n"},{"title":"card_578","front":"What is the rule of thumb before optimizing or parallelizing?","back":"Ensure the code works correctly first. Then, if you want to get fancy, you can begin to optimize your code for greater speed.\n"},{"title":"card_579","front":"Does Python have an opcode cache?","back":"In a way. It outputs a .pyc file, containing the bytecode. When a module is imported for the first time, or when the source is more recent than the current compiled file, a .pyc file containing the compiled code will usually be created in the same directory as the .py file. When you run the program next time, Python uses this file to skip the compilation step.\n"},{"title":"card_580","front":"Design a URL shortening service.","back":"ask:\n"},{"title":"card_581","front":"How would you design the feature in LinkedIn where it computes how many hops there are between you and another person?","back":"ask:\n"},{"title":"card_582","front":"If you were to design a web platform for online chess games, how would you do that?","back":"ask:\n-\n"},{"title":"card_583","front":"What are some key things to remember when scaling a large system?","back":"1) Asynchronous is good (use queues, topics/pub-sub)\n2) Parallel is good (multi-threading, load balancing etc.)\n3) Avoid points of contention e.g. synchronization\n4) Avoid writing to disk until you must - cache like crazy\n5) Scale out not up\n6) At web scale the speed of light is a problem\n7) At web scale everything fails - networks, load balancers etc.\n"},{"title":"card_584","front":"What is Thrift?","back":"Apache Thrift is a framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between different languages. It handles serialization and has its own communication protocol.\nIDL-based.\n"},{"title":"card_585","front":"What is Memcache?","back":"An in-memory distributed hash table. It supports only a few commands but it is extremely efficient.\n"},{"title":"card_586","front":"How does/did Facebook use memcache and mySQL in 2009?","back":"No joins in production. They have many logical databases for all of their types: people, events, place info, etc. They treat the web tier as a CPU, memcache as system memory, and the database as disk. Everything has an ID and you use the ID to query memcache using a multiget. Any misses are fetched from the database and cached in memcache.\n"},{"title":"card_587","front":"What is an out-of-band cache?","back":"A cache layer that does not synch with persistent storage. When changes are made to the database, there are no notifications to synchronize with the cache. The cache entry would need to be updated or evicted by other means.\n"},{"title":"card_588","front":"What is a monad?","back":"In functional programming, monads are a way to build computer programs by joining simple components in predictable and robust ways. A monad is a structure that represents computations defined as sequences of steps: a type with a monad structure defines what it means to chain operations together, or nest functions of that type. This allows the programmer to build pipelines that process data in a series of steps (i.e. a series of actions applied to the data), in which each action is decorated with additional processing rules provided by the monad. A monad is defined by a return operator that creates values, and a bind operator used to link the actions in the pipeline.\n"},{"title":"card_589","front":"What is pyramidpypi?","back":"A self-hosted mirror of pypi.\n"},{"title":"card_590","front":"Big Omega represents what?","back":"A lower bound on the growth of a function. f grows at least as fast as g.\n"},{"title":"card_591","front":"Theta represents what?","back":"A tight asymptotic bound on a function, in other words if both f and g have approximately the same rate of growth.\n"},{"title":"card_592","front":"For graph problems, the complexity Theta(N + M) is known as what?","back":"linear in the graph size\n"},{"title":"card_593","front":"What is a better way of saying \"at least O(n^2)\"?","back":"big Omega(n^2)\n"},{"title":"card_594","front":"What is data normalization?","back":"Normalization is a systematic approach of decomposing tables to eliminate data redundancy and undesirable characteristics like insertion, update and deletion anomalies.\n\nNormalization is used for mainly two purpose,\n- eliminating redundant (useless) data\n- ensuring data dependencies make sense\n"},{"title":"card_595","front":"What are the requirements for first normal form?","back":"- each cell has a single value\n- all items in a column must be of the same type\n- rows are uniquely identified by a unique ID or a composite key\n"},{"title":"card_596","front":"What are the requirements for second normal form?","back":"All attributes (non-key columns) are dependent on the key\n"},{"title":"card_597","front":"What are the requirements for third normal form?","back":"All fields can only be determined by the key in the table and no other column.\n"},{"title":"card_598","front":"What are the requirements for fourth normal form?","back":"No multi-valued dependencies, meaning records should not be duplicated in a table just because more than one item is associated. This creates records that are duplicates except for one field.\n"},{"title":"card_599","front":"What are some use cases of Hadoop?","back":"- reporting on user behavior over many events\n- log processing of 100s of billions of rows\n"},{"title":"card_600","front":"What are some solid principles to keep in mind for scaling?","back":"- Keep it very simple\n- Don’t re-invent the wheel\n- Go with boring, proven and well-supported technologies when you can\n- Build for what you will need over the next 12-18 months\n- Make different things look the same\n- Cache to protect the database\n- Good enough is good enough\n"},{"title":"card_601","front":"What is gunicorn?","back":"A Python WSGI HTTP Server\n"},{"title":"card_602","front":"What is WSGI?","back":"WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request. It was outlined in PEP 3333.\n\nA WSGI server (meaning WSGI compliant) only receives the request from the client, pass it to the application and then send the response returned by the application to the client.\n"},{"title":"card_603","front":"What is Fabric?","back":"Fabric is a Python (2.5-2.7) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.\n"},{"title":"card_604","front":"What is Apache Solr?","back":"Solr is an open source enterprise search platform built on Apache Lucene.\nSolr is highly reliable, scalable and fault tolerant, providing distributed indexing, replication and load-balanced querying, automated failover and recovery, centralized configuration and more.\n"},{"title":"card_605","front":"What is munin?","back":"Graph metrics and alerting.\n"},{"title":"card_606","front":"What tends to become an issue as you add services in a datacenter and have to ping more caches and services to fulfill a request?","back":"Fan-in, where you can overload routers due to increased internal network traffic.\n"},{"title":"card_607","front":"What can Redis be used for?","back":"- a noSQL key-value store\n- caches\n- queues\n"},{"title":"card_608","front":"What is a benefit of sharding a database as it grows, and what determines the size?","back":"Keeping the index in cache ensures a user lookup doesn't have to hit the disk, lookups can be served from RAM. How much RAM you have will determine the index size which will hint at the underlying data size.\n"},{"title":"card_609","front":"Why do most businesses end up sharding as they scale?","back":"To support massive concurrent writes.\n"},{"title":"card_610","front":"What is a message broker?","back":"Message broker is an intermediary program module that translates a message from the formal messaging protocol of the sender to the formal messaging protocol of the receiver. Message brokers are elements in telecommunication networks where software applications communicate by exchanging formally-defined messages. Message brokers are a building block of Message oriented middleware.\n"},{"title":"card_611","front":"What are some examples of message brokers?","back":"Apache ActiveMQ\nApache Kafka\nApache Qpid\nCelery\nGearman\nHornetQ (Red Hat)\nIBM Integration Bus\nJBoss Messaging (JBoss)\nJORAM\nMicrosoft BizTalk Server (Microsoft)\nMicrosoft Azure Service Bus (Microsoft)\nNATS (MIT Open Source License, written in Go)\nOpen Message Queue\nOracle Message Broker (Oracle Corporation)\nQDB (Apache License 2.0, supports message replay by timestamp)\nRabbitMQ (Mozilla Public License, written in Erlang)\nSAP PI (SAP AG)\nSpread Toolkit\nTarantool, a NoSQL database, with a set of stored procedures for message queues\nWSO2 Message Broker\nEnduro/X Transactional Message Queue (TMQ)\n"},{"title":"card_612","front":"What is Ehcache?","back":"Ehcache is an open source, standards-based cache that boosts performance, offloads your database, and simplifies scalability. It's the most widely-used Java-based cache.\n"},{"title":"card_613","front":"Timing of a L1 cache reference?","back":"0.5 nanoseconds (ns)\n"},{"title":"card_614","front":"Timing of a branch misprediction?","back":"5 nanoseconds (ns)\n"},{"title":"card_615","front":"Timing of a L2 cache reference?","back":"7 nanoseconds (ns)\n"},{"title":"card_616","front":"Timing of a mutex lock/unlock?","back":"25 nanoseconds (ns)\n"},{"title":"card_617","front":"Timing of a main memory reference?","back":"100 nanoseconds (ns)\n"},{"title":"card_618","front":"Timing to compress 1KB?","back":"3,000 nanoseconds (3 microseconds)\n"},{"title":"card_619","front":"Time to send 2K bytes over 1 Gbps network?","back":"10,000 nanoseconds (0.01 ms)\n"},{"title":"card_620","front":"Time to read 4KB randomly from an SSD?","back":"150,000 nanoseconds (0.15 ms)\n"},{"title":"card_621","front":"Timing to read 1MB sequentially from memory?","back":"250,000 nanoseconds (0.25 ms)\n"},{"title":"card_622","front":"Timing of a disk seek?","back":"10,000,000 nanoseconds (10 ms)\n"},{"title":"card_623","front":"Time to read 1MB sequentially from an SSD?","back":"1,000,000 nanoseconds (1 ms)\n4x memory\n"},{"title":"card_624","front":"Timing to read 1MB sequentially from disk?","back":"20,000,000 nanoseconds (20 ms)\n80x memory\n20x SSD\n"},{"title":"card_625","front":"Timing to send a packet CA -> Netherlands -> CA?","back":"150,000,000 nanoseconds (150 ms)\n"},{"title":"card_626","front":"Timing of a context switch between processes?","back":"3000 nanoseconds\n"},{"title":"card_627","front":"Timing of fork()?","back":"Between 70,000 and 160,000 nanoseconds.\n"},{"title":"card_628","front":"What is the timing overhead for a system call?","back":"400 nanoseconds\n"},{"title":"card_629","front":"What is Kafka?","back":"Apache Kafka is pub-sub messaging rethought as a distributed commit log.\nKafka is a distributed, partitioned, replicated commit log service. It provides the functionality of a messaging system, but with a unique design.\nA single Kafka broker can handle hundreds of megabytes of reads and writes per second from thousands of clients.\n"},{"title":"card_630","front":"What is GAE?","back":"Google App Engine is a platform for building scalable web applications and mobile backends. App Engine provides you with built-in services and APIs such as NoSQL datastores, memcache, and a user authentication API, common to most applications.\n"},{"title":"card_631","front":"What is GDS?","back":"Google Cloud Datastore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. Cloud Datastore features include:\n\nAtomic transactions.\nMassive scalability with high performance.\nFlexible storage and querying of data.\nBalance of strong and eventual consistency. \nEncryption at rest.\nFully managed with no planned downtime.\n"},{"title":"card_632","front":"What is the problem that serialization introduces?","back":"The overhead of serializing and deserializing. It's all expensive, and for Python, it can be terribly slow.\n"},{"title":"card_633","front":"What does the Python bisect module do?","back":"The bisect module, part of the standard library, provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach.\n"},{"title":"card_634","front":"What is PycURL?","back":"PycURL is a Python interface to libcurl. PycURL can be used to fetch objects identified by a URL from a Python program, similar to the urllib Python module. PycURL is mature, very fast, and supports a lot of features.\nPycURL is targeted at an advanced developer - if you need dozens of concurrent, fast and reliable connections or any of the sophisticated features listed above then PycURL is for you.\nThe main drawback of PycURL is that it is a relatively thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl's C API.\n"},{"title":"card_635","front":"How does PycURL compare to requests?","back":"PycURL can handle a large number of multiple concurrent requests. When reusing connections, it can perform more than 2,000 requests per second.\n\npycurl takes about 73 CPU-microseconds to issue a request when reusing a connection\nrequests takes about 526 CPU-microseconds to issue a request when reusing a connection\npycurl takes about 165 CPU-microseconds to open a new connection and issue a request (no connection reuse), or ~92 microseconds to open\nrequests takes about 1078 CPU-microseconds to open a new connection and issue a request (no connection reuse), or ~552 microseconds to open\n"},{"title":"card_636","front":"What is ZooKeeper?","back":"Apache ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. All of these kinds of services are used in some form or another by distributed applications. Each time they are implemented there is a lot of work that goes into fixing the bugs and race conditions that are inevitable. Because of the difficulty of implementing these kinds of services, applications initially usually skimp on them, which make them brittle in the presence of change and difficult to manage. Even when done correctly, different implementations of these services lead to management complexity when the applications are deployed.\nHas Java and C interfaces.\n"},{"title":"card_637","front":"What is orthogonality?","back":"In mathematical terms, it means being perpendicular.\n\nOrthogonality in programming language design is the ability to use various language features in arbitrary combinations with consistent results.\n\nOrthogonality is a system design property which guarantees that modifying the technical effect produced by a component of a system neither creates nor propagates side effects to other components of the system. Typically this is achieved through the separation of concerns and encapsulation, and it is essential for feasible and compact designs of complex systems. The emergent behavior of a system consisting of components should be controlled strictly by formal definitions of its logic and not by side effects resulting from poor integration, i.e., non-orthogonal design of modules and interfaces. Orthogonality reduces testing and development time because it is easier to verify designs that neither cause side effects nor depend on them.\n"},{"title":"card_638","front":"When dealing with scaling, how can you deal with rapidly increasing counters, like YouTube video views?","back":"You can add randomness to a monotonic counter, because as long as people can see it is increasing somewhat monotonically, it doesn't need to be 100% accurate. And avoids need to lock it in a transaction.\n"},{"title":"card_639","front":"What is exponential backoff and when is it used?","back":"Binary exponential backoff or truncated binary exponential backoff refers to an algorithm used to space out repeated retransmissions of network or other service requests, often as part of congestion avoidance.\n"},{"title":"card_640","front":"What data structure could be used to efficiently manage a leaderboard?","back":"A b-tree where each node manages a subset of the range of the worst to best scores.\n"},{"title":"card_641","front":"What does adding jitter in system design help you avoid?","back":"If your system doesn’t jitter then you get thundering herds. Distributed applications are really weather systems. Debugging them is as deterministic as predicting the weather. Jitter introduces more randomness because surprisingly, things tend to stack up.\n"},{"title":"card_642","front":"What is an example of adding jitter to a caching system?","back":"Cache expirations. For a popular video they cache things as best they can. The most popular video they might cache for 24 hours. If everything expires at one time then every machine will calculate the expiration at the same time. This creates a thundering herd.\nBy jittering you are saying randomly expire between 18-30 hours. That prevents things from stacking up. They use this all over the place. Systems have a tendency to self synchronize as operations line up and try to destroy themselves. Fascinating to watch. You get slow disk system on one machine and everybody is waiting on a request so all of a sudden all these other requests on all these other machines are completely synchronized. This happens when you have many machines and you have many events. Each one actually removes entropy from the system so you have to add some back in.\n"},{"title":"card_643","front":"What value can you make cron or other system intervals so they don't coincide?","back":"Use distinct prime numbers for periodicities.\n"},{"title":"card_644","front":"What Python package provides tools for adapting or extending functions and other callable objects, without completely rewriting them?","back":"functools\noffers:\nDecorators\nComparison\nRich Comparison\nCollation Order\nCaching\nReducing a Data Set\nGeneric Functions\n"},{"title":"card_645","front":"What is a proxy server?","back":"A proxy server is an intermediate piece of hardware/software that receives requests from clients and relays them to the backend origin servers. Typically, proxies are used to filter requests, log requests, or sometimes transform requests (by adding/removing headers, encrypting/decrypting, or compression).\n"},{"title":"card_646","front":"What is collapsed forwarding?","back":"A proxy server can collapse the same (or similar) requests together into one request, and then return the single result to the requesting clients.\n\nAnother great way to use the proxy is to not just collapse requests for the same data, but also to collapse requests for data that is spatially close together in the origin store (consecutively on disk).\n"},{"title":"card_647","front":"What should be handling requests first, a proxy server or a cache?","back":"Generally it is best to put the cache in front of the proxy. This is because the cache is serving data from memory, it is very fast, and it doesn't mind multiple requests for the same result. But if the cache was located on the other side of the proxy server, then there would be additional latency with every request before the cache, and this could hinder performance.\n"},{"title":"card_648","front":"What are some popular proxies?","back":"HAProxy\nSquid\nVarnish\n"},{"title":"card_649","front":"Why do indexes tend to slow down writes?","back":"Since you must both write the data and update the index.\n"},{"title":"card_650","front":"What is the role of a load balancer?","back":"The role is to distribute load across a set of nodes responsible for servicing requests. This allows multiple nodes to transparently service the same function in a system. Their main purpose is to handle a lot of simultaneous connections and route those connections to one of the request nodes, allowing the system to scale to service more requests by just adding nodes.\n"},{"title":"card_651","front":"What is a drawback of advanced features in a load balancer?","back":"Advanced features can make problem diagnosis cumbersome. For example, when it comes to high load situations, load balancers will remove nodes that may be slow or timing out (because of too many requests), but that only exacerbates the situation for the other nodes.\n"},{"title":"card_652","front":"What is a benefit of adding asynchrony to a system?","back":"It keeps clients from holding connections to servers when waiting for a response for a task that could simply be deferred. This reduces load on servers that are performing writes, for example, and lets them perform a task when ready, not on-demand.\n"},{"title":"card_653","front":"What is the difference between a synchronous system and an asynchronous system?","back":"In a synchronous system, there is no differentiation between request and reply, and they therefore cannot be managed separately. In an asynchronous system the client requests a task, the service responds with a message acknowledging the task was received, and then the client can periodically check the status of the task, only requesting the result once it has completed.\n\nWhile the client is waiting for an asynchronous request to be completed it is free to perform other work, even making asynchronous requests of other services.\n"},{"title":"card_654","front":"What are some examples of well-known queue (or can act as a queue) software?","back":"BeanstalkD\nRabbitMQ\nActiveMQ\nBeanstalkD\nRedis\n"},{"title":"card_655","front":"Does asynchronous code tend to be CPU-bound or I/O bound?","back":"Asynchronous code tends to be CPU bound, because anything that would block is simply deferred to later, until the blocking operation completes. This means that threads in asynchronous / non-blocking applications are much more likely to use their full time quantum before the kernel scheduler preempts them.\n"},{"title":"card_656","front":"What is the optimal number of threads?","back":"And if there's the same number of runnable threads as there are hardware threads, the kernel is very likely to reschedule threads on the same core, which significantly helps performance.\n"},{"title":"card_657","front":"What is the typical time slice for a process on a Linux box?","back":"Linux kernels are often compiled with HZ=100, which entails that processes are given time slices of 10ms.\n"},{"title":"card_658","front":"How does Linux handle CPU affinity?","back":"Default Linux kernels don't do a good job at keeping CPU affinity, even on idle machines. You must explore alternative schedulers or use taskset or cpuset to control affinity yourself.\n"},{"title":"card_659","front":"What is futex?","back":"A futex (short for \"fast userspace mutex\") is a Linux kernel system call that programmers can use to implement basic locking, or as a building block for higher-level locking abstractions such as semaphores and POSIX mutexes or condition variables.\n"},{"title":"card_660","front":"How do context switches perform under virtualization?","back":"On average, it's 2.5x to 3x more expensive to do a context switch when using virtualization. My guess is that this is due to the fact that the guest OS can't update the page table itself, so when it attempts to change it, the hypervisor intervenes, which causes an extra 2 context switches (one to get inside the hypervisor, one to get out, back to the guest OS).\n"},{"title":"card_661","front":"What is a Frame Check Sequence?","back":"The Frame Check Sequence (FCS) field is used to determine if errors occurred in the transmission and reception of the frame. Error detection is added at the Data Link layer because this is where data is transferred across the media.\n"},{"title":"card_662","front":"How does Google handle a search request?","back":"Scatter/gather\nIn this model, the dispatcher multicast the request to all workers of the pool. Each worker will compute a local result and send it back to the dispatcher, who will consolidate them into a single response and then send back to the client.\n"},{"title":"card_663","front":"What is an example of bulk synchronous processing?","back":"Parallel Graph Transformation\n\nThe main goal of Graph transformation is to modify the graph. This include modifying the properties of existing nodes and arcs, creating new arcs / nodes and removing existing arcs / nodes. The modification logic is provided by a user-defined function, which will be applied to all active nodes.\n"},{"title":"card_664","front":"Execution Orchestrator","back":"This model is based on an intelligent scheduler / orchestrator to schedule ready-to-run tasks (based on a dependency graph) across a clusters of dumb workers.\n\nexample: Microsoft Dryad\n"},{"title":"card_665","front":"What are 2 reasons for using a load balancer?","back":"horizontal scalability and redundancy\n"},{"title":"card_666","front":"What are balancing methods used by load balancers?","back":"assignment of a request: random, round-robin, random with weighting for machine capacity, etc\nmatched with current status (available for requests, not responding, elevated error rate, etc).\n"},{"title":"card_667","front":"What are the 3 choices in load balancers? The 3 kinds, not balancing mechanisms.","back":"- Smart client, a software based mechanism for determining the availability of a server.\n- Hardware load balancer, such as Citrix NetScaler, are remarkably expensive, and they are also \"non-trivial\" to configure.\n- Software load balancer: HAProxy\n"},{"title":"card_668","front":"What are 2 examples of in-memory caches?","back":"Memcached and Redis are both examples of in-memory caches\n"},{"title":"card_669","front":"What is write-through cache?","back":"Write-through cache directs write I/O onto cache and through to underlying permanent storage before confirming I/O completion to the host. This ensures data updates are safely stored on, for example, a shared storage array, but has the disadvantage that I/O still experiences latency based on writing to that storage. Write-through cache is good for applications that write and then re-read data frequently as data is stored in cache and results in low read latency.\n"},{"title":"card_670","front":"What is write-back cache?","back":"Write-back cache is where write I/O is directed to cache and completion is immediately confirmed to the host. This results in low latency and high throughput for write-intensive applications, but there is data availability exposure risk because the only copy of the written data is in cache. As we will discuss later, suppliers have added resiliency with products that duplicate writes. Users need to consider whether write-back cache solutions offer enough protection as data is exposed until it is staged to external storage. Write-back cache is the best performing solution for mixed workloads as both read and write I/O have similar response time levels.\n"},{"title":"card_671","front":"What is read-through cache?","back":"An item is accessed from cache, and if it's a cache miss, the data will be read from persistent storage (perhaps with a callback) and then placed into cache. The response is then sent back to the host.\n"},{"title":"card_672","front":"What is HDFS?","back":"Hadoop File System (HDFS) is a Java-based file system that provides scalable and reliable data storage, and it was designed to span large clusters of commodity servers.\n"},{"title":"card_673","front":"What is Hortonworks?","back":"Hortonworks is a software company focused on the development and support of Apache Hadoop, a framework that allows for the distributed processing of large data sets across clusters of computers.\n"},{"title":"card_674","front":"What is a platform layer?","back":"Web applications to communicate with a platform layer which in turn communicates with your databases. \n\nFirst, separating the platform and web application allow you to scale the pieces independently. If you add a new API, you can add platform servers without adding unnecessary capacity for your web application tier. \n\nSecond, adding a platform layer can be a way to reuse your infrastructure for multiple products or interfaces (a web application, an API, an iPhone app, etc) without writing too much redundant boilerplate code for dealing with caches, databases, etc.\n\nThird, a sometimes underappreciated aspect of platform layers is that they make it easier to scale an organization. At their best, a platform exposes a crisp product-agnostic interface which masks implementation details. If done well, this allows multiple independent teams to develop utilizing the platform's capabilities, as well as another team implementing/optimizing the platform itself.\n"},{"title":"card_675","front":"What is multi-homing?","back":"Running a service across multiple datacenters.\n"},{"title":"card_676","front":"Where is weak consistency OK?","back":"- caching\n- VOIP\n- real-time mutiplayer games\n"},{"title":"card_677","front":"What is the Paxos algorithm?","back":"Paxos is a family of protocols for solving consensus in a network of unreliable processors. Consensus is the process of agreeing on one result among a group of participants. This problem becomes difficult when the participants or their communication medium may experience failures.\n"},{"title":"card_678","front":"What problem does consistent hashing help solve?","back":"If you're using a caching scheme like server = hash(i) mod m, and one server in the cluster drops out, consistent hashing is needed to avoid swamping your servers when all the caches need to rehash their entities.\n"},{"title":"card_679","front":"What is the relationship between consistent hashing and memcache?","back":"Consistent hashing can be used with memcache not even knowing about it. It is interesting to note that it is only the client that needs to implement the consistent hashing algorithm - the memcached server is unchanged.\n"},{"title":"card_680","front":"What are some examples of NoSQL solutions?","back":"Google BigTable\nHBase (based on Hadoop)\nHypertable\nAmazon DynamoDB\nVoldemort\nCassandra\nRiak\nRedis\nCouchDB\nMongoDB\n"},{"title":"card_681","front":"What is Paxos an example of?","back":"quorum-based 2PC (2 phase commit) protocol\n"},{"title":"card_682","front":"What is MVCC?","back":"Multiversion concurrency control (MCC or MVCC), is a concurrency control method commonly used by database management systems to provide concurrent access to the database and in programming languages to implement transactional memory.\n"},{"title":"card_683","front":"What is the S in SOLID?","back":"The single responsibility principle. There should never be more than one reason for a class to change. We can relate the “reason to change” to “the responsibility of the class”. So each responsibility would be an axis for change.\n"},{"title":"card_684","front":"What does concurrent.futures do?","back":"The concurrent.futures modules provides interfaces for running tasks using pools of thread or process workers. The APIs are the same, so applications can switch between threads and processes with minimal changes.\n"},{"title":"card_685","front":"What is the O in SOLID?","back":"The Open/Closed Principle (OCP) states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.\n\"open for extension / closed for modifications\"\n\n--\n\nDuring the 1990s, the open/closed principle became popularly redefined to refer to the use of abstracted interfaces, where the implementations can be changed and multiple implementations could be created and polymorphically substituted for each other.\n\nIn contrast to Meyer's usage, this definition advocates inheritance from abstract base classes. Interface specifications can be reused through inheritance but implementation need not be.\n"},{"title":"card_686","front":"What is RTTI?","back":"run time type identification\n"},{"title":"card_687","front":"Which SOLID principle is \"Make all Member Variables Private.\" helping to enforce?","back":"The open/closed principle (OCP)\n"},{"title":"card_688","front":"What is the L in SOLID?","back":"The Liskov substitution principle (LSP)\nWe must make sure that the new derived classes just extend without replacing the functionality of old classes. Otherwise the new classes can produce undesired effects when they are used in existing program modules.\n\nLiskov's Substitution Principle states that if a program module is using a Base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.\n\nThis principle is just an extension of the Open Close Principle and it means that we must make sure that new derived classes are extending the base classes without changing their behavior.\n"},{"title":"card_689","front":"What is the I in SOLID?","back":"The Interface Segregation Principle (ISP) states that clients should not be forced to implement interfaces they don't use. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one submodule.\n"},{"title":"card_690","front":"What is the D in SOLID?","back":"Dependency inversion principle (DIP)\nHigh-level modules should not depend on low-level modules. Both should depend on abstractions.\nAbstractions should not depend on details. Details should depend on abstractions.\n"},{"title":"card_691","front":"What are 3 things CDNs use to ensure availability?","back":"Local clustering can improve fault-tolerance and scalability. Mirroring (deploying clusters in a few locations) and multihoming (using multiple ISPs to connect to the Internet). \nClustering, mirroring, and multihoming are common approaches for sites with stringent reliability and scalability needs.\n"},{"title":"card_692","front":"What is hyper-threading?","back":"Hyper-threading enables a single processor core to be used for two or more concurrent executions with just a little extra hardware.\n"},{"title":"card_693","front":"What is DMA?","back":"DMA (Direct Memory Access) allows devices, with the help of the Northbridge, to store and receive data in RAM directly without the intervention of the CPU.\n"},{"title":"card_694","front":"What does NUMA stand for?","back":"Non-Uniform Memory Architecture\n"},{"title":"card_695","front":"Where are SRAM and DRAM used?","back":"SRAMs are used in Caches because of higher speed and DRAMs are used for main memory in a PC because of higher densities.\n"},{"title":"card_696","front":"What is the difference between SRAM and DRAM?","back":"DRAM stands for Dynamic Random Access Memory. It is a type of semiconductor memory in which the memory is stored in the form of a charge. Each memory cell in a DRAM is made of a transistor and a capacitor. The data is stored in the capacitor. Capacitors loose charge due to leakage and hence DRAM's are volatile devices. To keep the data in the memory, the device must be regularly refreshed whereas SRAM is static, so it will retain a value as long as power is supplied. SRAM is typically faster than DRAM since it doesn't have refresh cycles. Since each SRAM memory cell is comprised of 6 Transistors unlike a DRAM memory cell, which is comprised of 1 Transistor and 1 Capacitor, the cost per memory cell is far greater in an SRAM compared to a DRAM.\n"},{"title":"card_697","front":"What is the difference between a CPU core and a CPU thread?","back":"The difference between a core and a thread is that separate cores have separate copies of (almost) all the hardware resources. The cores can run completely independently unless they are using the same resources–e.g., the connections to the outside - at the same time. Threads, on the other hand, share almost all of the processor’s resources.\nIntel’s implementation of threads has only separate registers for the threads and even that is limited, some registers\nare shared.\n"},{"title":"card_698","front":"What is SMP?","back":"symmetric multi-processor\n\nIn symmetric multi-processor (SMP) systems the caches of the CPUs cannot work independently from each other. All processors are supposed to see the same memory content at all times. The maintenance of this uniform view of memory is called “cache coherency”.\n"},{"title":"card_699","front":"How does a multi-processor CPU maintain cache coherency?","back":"- A dirty cache line is not present in any other processor’s cache.\n- Clean copies of the same cache line can reside in arbitrarily many caches.\n"},{"title":"card_700","front":"What is Colossus?","back":"the successor to the Google File System\n"},{"title":"card_701","front":"What is Spanner?","back":"Spanner is a scalable, globally-distributed database designed, built, and deployed at Google. At the highest level of abstraction, it is a database that shards data across many sets of Paxos state machines in datacenters spread all over the world. Replication is used for global availability and geographic locality; clients automatically failover between replicas. Spanner automatically reshards data across machines as the amount of data or the number of servers changes, and it automatically migrates data across machines (even across datacenters) to balance load and in response to failures. Spanner is designed to scale up to millions of machines across hundreds of datacenters and trillions of database rows.\n"},{"title":"card_702","front":"What is Marzullo's algorithm?","back":"Marzullo's algorithm, is an agreement algorithm used to select sources for estimating accurate time from a number of noisy time sources. A refined version of it, renamed the \"intersection algorithm\", forms part of the modern Network Time Protocol.\n"},{"title":"card_703","front":"What is Google File System?","back":"A scalable distributed file system for large distributed data-intensive applications. It provides fault tolerance while running on inexpensive commodity hardware, and it delivers high aggregate performance to a large number of clients.\nIt deals with multi-GB and TB files by appending to files, as that is the predominant usage pattern of large data files.\n"},{"title":"card_704","front":"What is BNF?","back":"BNF (Backus Normal Form or Backus–Naur Form) is one of the two main notation techniques for context-free grammars, often used to describe the syntax of languages used in computing, such as computer programming languages, document formats, instruction sets and communication protocols; the other main technique for writing context-free grammars is the van Wijngaarden form.\n"},{"title":"card_705","front":"What is MapReduce?","back":"MapReduce, developed by Google in 2004, is a programming model and an associated implementation for processing and generating large data sets. Users specify a map function that processes a key/value pair to generate a set of intermediate key/value pairs, and a reduce function that merges all intermediate values associated with the same intermediate key.\n"},{"title":"card_706","front":"What is a Zipf distribution?","back":"The Zipf distribution, sometimes referred to as the zeta distribution, is a discrete distribution commonly used in linguistics, insurance, and the modeling of rare events.\n"},{"title":"card_707","front":"The memory addresses returned by the malloc function are typically aligned to at least ___ bytes.","back":"8\n"},{"title":"card_708","front":"What is AddressSanitizer?","back":"AddressSanitizer is a fast memory error detector. AddressSanitizer finds out-of-bounds (for heap, stack, and globals) accesses and use-after-free bugs at the cost of 73% slowdown on average and a 3.4x memory size; the tool has no false positives.\nAddressSanitizer uses shadow memory to provide accurate and immediate bug detection. The conventional wisdom is that shadow memory either incurs high overhead through multi-level mapping schemes or imposes prohibitive address space requirements by occupying a large contiguous region. Our novel shadow state encoding reduces our shadow space footprint enough that we can use a simple mapping, which can be implemented with low overhead.\nIt has been included as a compilation option in LLVM since 3.1.\n"},{"title":"card_709","front":"What is transitive closure?","back":"transitive closure can be thought of as constructing a data structure that makes it possible to answer reachability questions. That is, can one get from node a to node d in one or more hops?\n"},{"title":"card_710","front":"What is CUDA?","back":"CUDA (Compute Unified Device Architecture) is a parallel computing platform and application programming interface (API) model created by NVIDIA.[1] It allows software developers and software engineers to use a CUDA-enabled graphics processing unit (GPU) for general purpose processing – an approach known as GPGPU. The CUDA platform is a software layer that gives direct access to the GPU's virtual instruction set and parallel computational elements, for the execution of compute kernels.[2]\n"},{"title":"card_711","front":"What is Borg?","back":"The first unified container-management system developed at Google. It was built to manage both long-running services and batch jobs.\n"},{"title":"card_712","front":"What is MPM?","back":"Within Google, MPM (Midas Package Manager) is used to build and deploy container images. It corresponds to the Docker image registry for Docker containers.\n"},{"title":"card_713","front":"What are 3 benefits of containers?","back":"1. Containers encapsulate the application environment, abstracting away many details of machines and operating systems from the application developer and the deployment infrastructure.\n2. Because well-designed containers and container images are scoped to a single application, managing containers means managing applications rather than machines. This shift of management APIs from machine-oriented to application oriented dramatically improves application deployment and introspection.\n3. Decoupling of image and OS makes it possible to provide the same deployment environment in both development and production, which, in turn, improves deployment reliability and speeds up development by reducing inconsistencies and friction.\n"},{"title":"card_714","front":"What is Chubby?","back":"A distributed lock service (master election) built on Borg.\n"},{"title":"card_715","front":"What does CSP stand for?","back":"Communicating Sequential Processes\n"},{"title":"card_716","front":"What is Protocol buffers?","back":"Protocol buffers (aka protobuf) are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data. IDL-based.\n\nYou define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.\n"},{"title":"card_717","front":"Why is using Protocol buffers better than pickling?","back":"Python pickling doesn't deal well with schema evolution, and also doesn't work very well if you need to share data with applications written in C++ or Java.\n"},{"title":"card_718","front":"What is gRPC?","back":"It’s an open source framework for RPC by Google. gRPC uses HTTP/2 and Google’s own Protobuf to provide a scalable and low latency communication. With gRPC comes a new version of Protobuf (proto3) for high performance binary serialization which includes new features and is easier to use than its predecessors.\n"},{"title":"card_719","front":"What is Redis?","back":"Redis is an in-memory data structure store, used as database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.\n"},{"title":"card_720","front":"What commands can be used to make a Redis queue somewhat reliable?","back":"LPUSH\nRPOPLPUSH - pop right, pushing onto another list for processing, atomically,\nBRPOPLPUSH - same as above, but blocking\nRPOP\n\nRedis is more susceptible to data loss in the event of abrupt termination or power failures.\n"},{"title":"card_721","front":"What is RabbitMQ?","back":"RabbitMQ is a messaging broker - an intermediary for messaging.\n\nMessages are routed through exchanges before arriving at queues. RabbitMQ features several built-in exchange types for typical routing logic. For more complex routing you can bind exchanges together or even write your own exchange type as a plugin.\n\nIt can be used as a durable queue, work queues, pub/sub, topic handler, and even for rpc.\n"},{"title":"card_722","front":"What is pika?","back":"Pika is a pure-Python implementation of the AMQP 0-9-1 protocol that tries to stay fairly independent of the underlying network support library. Can use with RabbitMQ.\n"},{"title":"card_723","front":"What is Celery?","back":"Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well. You use it with a message broker, and it manages the task execution.\n\nThe execution units, called tasks, are executed concurrently on a single or more worker servers using multiprocessing, Eventlet, or gevent. Tasks can execute asynchronously (in the background) or synchronously (wait until ready).\n\nThe recommended message broker is RabbitMQ, but support for Redis, Beanstalk, MongoDB, CouchDB, and databases (using SQLAlchemy or the Django ORM) is also available.\n"},{"title":"card_724","front":"What does amqp stand for?","back":"Advanced Message Queuing Protocol\n"},{"title":"card_725","front":"What is ZeroMQ?","back":"A socket-based system, can be used as a queue, pub/sub, etc.\n\nCarries messages across inproc, IPC, TCP, TIPC, multicast.\nSmart patterns like pub-sub, push-pull (pipeline), and router-dealer.\n"},{"title":"card_726","front":"What is ActiveMQ?","back":"Apache ActiveMQ is an open source message broker written in Java.\n"},{"title":"card_727","front":"What is IPC?","back":"Inter-process communication or interprocess communication (IPC) refers specifically to the mechanisms an operating system provides to allow processes it manages to share data. Typically, applications can use IPC categorized as clients and servers, where the client requests data and the server responds to client requests.\n"},{"title":"card_728","front":"What is Kafka?","back":"Apache Kafka is a distributed, partitioned, replicated commit log service. It provides the functionality of a messaging system, but with a unique design.\n"},{"title":"card_729","front":"What is MessagePack?","back":"MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.\n\nNo IDL.\n"},{"title":"card_730","front":"What is Avro?","back":"Apache Avro is a data serialization system. IDL-based.\nRich data structures. \nA compact, fast, binary data format. \nA container file, to store persistent data. \nRemote procedure call (RPC).\nCode generation is not required to read or write data files nor to use or implement RPC protocols. Code generation as an optional optimization, only worth implementing for statically typed languages.\n"},{"title":"card_731","front":"What is a Bloom filter?","back":"A Bloom filter is a data structure used to quickly test membership in a set where the number and size of possible elements would be very large. Too large to keep in memory.\nA Bloom filter is a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not, thus a Bloom filter has a 100% recall rate. In other words, a query returns either \"possibly in set\" or \"definitely not in set\". Elements can be added to the set, but not removed (though this can be addressed with a \"counting\" filter). The more elements that are added to the set, the larger the probability of false positives.\n"},{"title":"card_732","front":"How can you easily generate multiple hashes for the same element?","back":"Double hashing. This method gives you as many hashes as you need:\nhash(x,m) = (hasha(x) + i * hashb(x)) mod m\n\nIn Python:\nimport mmh3\nmmh3.hash64('foo') # two 64 bit signed ints, in a tuple\nnow you have 2 64-bit hashes. Substituting for i gives you multiple hashes for a Bloom filter.\n"},{"title":"card_733","front":"What is DFT?","back":"Discrete Fourier Transform - converts a finite sequence of equally-spaced samples of a function into an equivalent-length sequence of equally-spaced samples of the discrete-time Fourier transform (DTFT), which is a complex-valued function of frequency.\n"},{"title":"card_734","front":"What is FFTW?","back":"Developed at MIT, it's the Fastest Fourier Transform in the West.\n"},{"title":"card_735","front":"What data structure allows for insert and delete in constant time?","back":"An array, indexed by the value stored. Technically a bit vector.\n"},{"title":"card_736","front":"What is a cache-oblivious algorithm?","back":"A cache-oblivious algorithm does not mean that the algorithm does not take advantage of the cache; to the contrary, it does so quite effectively. What it means is that the algorithm does not need to know the cache line size; it works effectively for all cache line sizes simultaneously, removing the need to tune or optimize for a given machine.\n\nOptimal cache-oblivious algorithms are known for the Cooley–Tukey FFT algorithm, matrix multiplication, sorting, matrix transposition, and several other problems.\n"},{"title":"card_737","front":"How can you augment a splay tree so you can find how many items are between x and y?","back":"Store size of subtrees at each node. \nFind x, splay to root. Each splay, insert, and delete must maintain size in node.\nFind y, and along the way add up the sizes in the left subtrees, and 1 for each visited left-hand node.\nSplay y to root to ensure balance.\n"},{"title":"card_738","front":"In a maximum flow problem, what is the minimum cut?","back":"The min cut is the maximum flow through the graph.\n"},{"title":"card_739","front":"What is the Ford-Fulkerson algorithm?","back":"The Ford–Fulkerson method or Ford–Fulkerson algorithm (FFA) is a greedy algorithm that computes the maximum flow in a flow network. It is called a \"method\" instead of an \"algorithm\" as the approach to finding augmenting paths in a residual graph is not fully specified or it is specified in several implementations with different running times. The name \"Ford–Fulkerson\" is often also used for the Edmonds–Karp algorithm, which is a specialization of Ford–Fulkerson.\n"},{"title":"card_740","front":"What is the running time for the disjoint set data structure?","back":"Due to merging smaller disjoint sets into larger ones (called union by rank) (during union) and performing path compression (during find), the amortized time per operation is only O(alpha(n)), where alpha(n) is the inverse of the function and A is the extremely fast-growing Ackermann function. Since alpha(n) is the inverse of this function, alpha(n) is less than 5 for all remotely practical values of n. Thus, the amortized running time per operation is effectively a small constant.\n\nThe worst-case for find() is Theta(log u) where u is the number of unions, and no finds have been done to allow for path compression yet.\n"},{"title":"card_741","front":"In testing, what is an oracle?","back":"Software testers and software engineers can use an oracle as a mechanism for determining whether a test has passed or failed. The use of oracles involves comparing the output(s) of the system under test, for a given test-case input, to the output(s) that the oracle determines that product should have.\n"},{"title":"card_742","front":"What do you test interfaces with a trust boundary?","back":"With lots of different inputs, including random inputs to ensure that the system can handle or appropriately error out, not crash.\n"},{"title":"card_743","front":"What Python flag turns on optimizations and removes assertions from code?","back":"python -O\n"},{"title":"card_744","front":"Why is doing work in a constructor a bad thing?","back":"It can make your code harder to test.\n"},{"title":"card_745","front":"What should be avoided to ensure testing is easier/possible?","back":"- static methods and properties\n- final keyword\n- use of new in methods (use dependency injection)\n"},{"title":"card_746","front":"What is another name for a setter?","back":"A mutator\n"},{"title":"card_747","front":"What is another name for a getter?","back":"An accessor.\n"},{"title":"card_748","front":"What are some guidelines to keep in mind to not violate the dependency inversion principle?","back":"- No variable should have a concrete class type. An abstract type is better.\n- No class should derive from a concrete class.\n- No method should override an implemented method of any of its base classes.\n\nThese are guidelines and may not be feasible all the time.\n"},{"title":"card_749","front":"What is another name for O(2^n)?","back":"Exponential growth\n"},{"title":"card_750","front":"What is another name for O(n^4)?","back":"Quartic growth\n"},{"title":"card_751","front":"What does big-O mean? (briefly)","back":"It never gets as big as this.\nGrowth will never be slower as this.\n"},{"title":"card_752","front":"What does big-Omega mean? (briefly)","back":"It's at least as big as this.\nGrowth will never be slower as this.\n"},{"title":"card_753","front":"What is a trap/exception?","back":"A special instruction that a program performs to interrupt the process and give control to the kernel.\n"},{"title":"card_754","front":"What does the scheduler do?","back":"Schedulers are special system software which handles process scheduling in various ways. Their main task is to select the jobs to be submitted into the system and to decide which process to run.\n"},{"title":"card_755","front":"What are the 2 hardware modes?","back":"kernel mode and user mode\n"},{"title":"card_756","front":"What is a PCB and what does it have?","back":"Process control block - It holds a complete snapshot of the state of the process.\n"},{"title":"card_757","front":"What is stored in a TCB?","back":"registers\nprogram counter\nstack counter\n"},{"title":"card_758","front":"What is separate chaining?","back":"In hash table conflict resolution, each bucket is independent and has some sort of linked list of entries with the same index. The time for hash table operations is the time to find the bucket (which is constant) plus the time for the list operation.\n\nIn a good hash table, each bucket has zero or one entries, and sometimes two or three, but rarely more than that. Therefore, structures that are efficient in time and space for these cases are preferred. Structures that are efficient for a fairly large number of entries per bucket are not needed or desirable. If these cases happen often, the hashing function needs to be fixed.\n"},{"title":"card_759","front":"What is open addressing?","back":"In hash table conflict resolution, all entry records are stored in the bucket array itself. When a new entry has to be inserted, the buckets are examined, starting with the hashed-to slot and proceeding in some probe sequence, until an unoccupied slot is found. When searching for an entry, the buckets are scanned in the same sequence, until either the target record is found, or an unused array slot is found, which indicates that there is no such key in the table. The name \"open addressing\" refers to the fact that the location (\"address\") of the item is not determined by its hash value. (This method is also called closed hashing; it should not be confused with \"open hashing\" or \"closed addressing\" that usually mean separate chaining.)\n"},{"title":"card_760","front":"What is the length of the longest chain in a hash table using separate chaining?","back":"O(1 + alpha) where alpha is the load factor, n/m.\n"},{"title":"card_761","front":"Since uniform hashing is difficult to achieve in practice, what is a great alternative?","back":"double hashing\n"},{"title":"card_762","front":"How can you test if a number is odd in bitwise operations?","back":"return (x & 1)\n"},{"title":"card_763","front":"How can you test if a number is even in bitwise operations?","back":"return (x & 1) == 0\n"},{"title":"card_764","front":"What order of node and its children are involved in a preorder traversal?","back":"node\nleftChild\nrightChild\n"},{"title":"card_765","front":"What order of node and its children are involved in a postorder traversal?","back":"leftChild\nrightChild\nnode\n"},{"title":"card_766","front":"What order of node and its children are involved in an inorder traversal?","back":"leftChild\nnode\nrightChild\n"},{"title":"card_767","front":"What is another name for a breadth-first search traversal?","back":"Level-order traversal.\n"},{"title":"card_768","front":"Code: Compute the power set of a set of integers S.","back":"How?\n"},{"title":"card_769","front":"What is the proper name for Endianness?","back":"octet order\n"},{"title":"card_770","front":"Where can octet order (Endianness) problems crop up in files?","back":"In binary files, if you aren't consistent with choosing an order. Files encoded in utf8 or ASCII don't have this issue.\n"},{"title":"card_771","front":"What defines a complete binary tree, and give an example?","back":"The same number of nodes at all levels of the tree, except at leaf level where it fills in left to right. A heap stored as an array is an example.\n"},{"title":"card_772","front":"In a heap, with a 0-based array, what is parent of i?","back":"floor((i-1)/2)\n"},{"title":"card_773","front":"In a heap, with a 0-based array, what is left child of i?","back":"2i + 1\n"},{"title":"card_774","front":"In a heap, with a 0-based array, what is right child of i?","back":"2i + 2\n"},{"title":"card_775","front":"In a heap, with a 1-based array, what is right child of i?","back":"2i + 1\n"},{"title":"card_776","front":"In a heap, with a 1-based array, what is left child of i?","back":"2i\n"},{"title":"card_777","front":"In a heap, with a 0-based array, what is parent of i?","back":"floor(i/2)\n"},{"title":"card_778","front":"What is the height of a m-ary heap?","back":"log base m of n\n"},{"title":"card_779","front":"What is a 2-3-4 tree?","back":"2–3–4 tree (also called a 2–4 tree) is a self-balancing data structure that is commonly used to implement dictionaries. The numbers mean a tree where every node with children (internal node) has either two, three, or four child nodes:\n\n- 2-node has one data element, and if internal has two child nodes;\n- 3-node has two data elements, and if internal has three child nodes;\n- 4-node has three data elements, and if internal has four child nodes.\n"},{"title":"card_780","front":"What is the complexity of all operations on a splay tree?","back":"O(log n) on average.\nA single operation Theta(n) in the worst case.\n"},{"title":"card_781","front":"What is the maximum height of a red-black tree?","back":"2 log n\n"},{"title":"card_782","front":"In a b-tree, how many children are there per node?","back":"root: 1 to 2t-1 keys\nnon-root: t-1 to 2t-1 keys\nt could be up to 100, or more.\nThere are n keys and n+1 children.\nLeaves are all the same level.\n"},{"title":"card_783","front":"What does the max degree of a b-tree depend on?","back":"The number of items being stored, and page size based on disk characteristics.\n"},{"title":"card_784","front":"A b-tree's data is organized to correspond with what?","back":"Pages on disk.\n"},{"title":"card_785","front":"Give an example of how a b-tree might be organized.","back":"1024 children per node.\nStore root in memory.\n3 nodes accessed gets us 1024^3 disk pages.\n4 nodes accessed gets us 1024^4 disk pages.\n"},{"title":"card_786","front":"On descending a b-tree, what's the rule?","back":"Never step into a minimal node.\n"},{"title":"card_787","front":"On insertion in a b-tree, what's the rule?","back":"Never step into a full node.\n"},{"title":"card_788","front":"How many nodes of k leaves are in a compressed trie (big-O)?","back":"O(k) nodes with k leaves due to compression.\n"},{"title":"card_789","front":"What is a suffix tree?","back":"A suffix tree is a compressed trie containing all the suffixes of the given text as their keys and positions in the text as their values. Suffix trees allow particularly fast implementations of many important string operations.\n\nThe construction of such a tree for the string S takes time and space linear in the length of S. Once constructed, several operations can be performed quickly, for instance locating a substring in S, locating a substring if a certain number of mistakes are allowed, locating matches for a regular expression pattern etc. Suffix trees also provide one of the first linear-time solutions for the longest common substring problem. These speedups come at a cost: storing a string's suffix tree typically requires significantly more space than storing the string itself.\n"},{"title":"card_790","front":"In brief, how does selection sort work?","back":"Find the minimum item on each pass, past the previous minimum, and swap it into the leftmost position after the previous minimum.\n"},{"title":"card_791","front":"When can insertion sort run in n log n time?","back":"Load into a binary search tree. Then inorder traversal.\n"},{"title":"card_792","front":"How can you speed up selection sort with a heap?","back":"Replace the unsorted portion with a min-heap. Gives O(log n) removal. Makes n log n overall.\n"},{"title":"card_793","front":"What data structure is well suited for a heap sort and which is bad?","back":"Array - good\nLinked list - clumsy\n"},{"title":"card_794","front":"What data structure is well suited for a merge sort and which is just okay?","back":"Linked list - a natural\nArray does not allow for in-place\n"},{"title":"card_795","front":"How can you optimize finding a pivot when the segment to pivot is large (not random choice)?","back":"Choose a median of three.\n"},{"title":"card_796","front":"What is counting sort?","back":"Counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently.\n"},{"title":"card_797","front":"What is radix sort?","back":"Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. \nTwo classifications of radix sorts are least significant digit (LSD) radix sorts and most significant digit (MSD) radix sorts. LSD radix sorts process the integer representations starting from the least digit and move towards the most significant digit. MSD radix sorts work the other way around.\n"},{"title":"card_798","front":"What is the counting sort running time?","back":"O(q + n) where q is the number of unique items. If q is in O(n), then linear time.\n"},{"title":"card_799","front":"What radix is most natural to use?","back":"A power of 2 radix.\n"},{"title":"card_800","front":"How would radix sort work for IEEE floating point numbers?","back":"Flip all bits for negative numbers, do sort, then flip back.\n"},{"title":"card_801","front":"How to choose q for radix sort?","back":"Choose q within a power of 2 of n. Ensures the number of passes is small. Best rule is n rounded down to the next power of 2.\nTo save memory, round sqrt(n) down to the next power of 2. Twice as many passes.\n"},{"title":"card_802","front":"What operations are a treap optimized for?","back":"- union\n- intersection\n- difference\n"},{"title":"card_803","front":"What is the Day–Stout–Warren (DSW) algorithm?","back":"The Day–Stout–Warren (DSW) algorithm is a method for efficiently balancing binary search trees — that is, decreasing their height to O(log n) nodes, where n is the total number of nodes. Unlike a self-balancing binary search tree, it does not do this incrementally during each operation, but periodically, so that its cost can be amortized over many operations.\n"},{"title":"card_804","front":"Is radix sort stable?","back":"Yes.\n"},{"title":"card_805","front":"What is the algorithmic time complexity of radix sort?","back":"O(digits)\n"},{"title":"card_806","front":"All comparison-based sorting is bounded by what complexity?","back":"Omega(n log n)\n"},{"title":"card_807","front":"What do you call a linear ordering of a directed graph of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering?","back":"Topological sort\n"},{"title":"card_808","front":"What is a good method for performing a topological sort?","back":"1. Calculate in-degree for each node. O(v + e)\n2. Go through 0s, add to queue.\n3. For each item in queue, look at each connection, and decrement in-degree of each, if they got to 0, add to queue, repeat.\n"},{"title":"card_809","front":"How many possible trees are there that span all nodes in a graph?","back":"4^n\n"},{"title":"card_810","front":"What is the time complexity of Prim's algorithm on an adjacency matrix?","back":"O(v^2)\n"},{"title":"card_811","front":"What is the time complexity of Prim's algorithm on an adjacency list and a binary heap?","back":"O(e log v)\nderived from:\nO((e + v) log v)\n"},{"title":"card_812","front":"What is the time complexity of Prim's algorithm on an adjacency list and a Fibonacci heap?","back":"O(e + v log v)\n"},{"title":"card_813","front":"What is the time complexity of Kruskal's algorithm?","back":"O(E log V)\nor\nO(e log e + e α(v) + v)\n"},{"title":"card_814","front":"What is Kruskal's algorithm?","back":"Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the least possible weight that connects any two trees in the forest. It is a greedy algorithm in graph theory as it finds a minimum spanning tree for a connected weighted graph adding increasing cost arcs at each step. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. If the graph is not connected, then it finds a minimum spanning forest (a minimum spanning tree for each connected component).\n"},{"title":"card_815","front":"How can you find the number of connected components?","back":"For each node:\n if node not yet visited, increment component count and do DFS.\n"},{"title":"card_816","front":"How can you get a topological sort with DFS?","back":"Do a DFS, and when each node is being marked as complete, add node to a list.\nReverse the list.\n"},{"title":"card_817","front":"How can you check for a cycle with DFS?","back":"for each neighbor node:\nif not marked as visited (and is not parent) then DFS\nelse it's a cycle\n"},{"title":"card_818","front":"How can you get the strongly connected components of a graph?","back":"1. DFS - calculate the finish times for each node\n2. Reverse the edges in the graph\n3. Call DFS on nodes in reverse graph in reverse order of finishing times.\n"},{"title":"card_819","front":"How do you reverse the edges in a directed graph represented as an adjacency matrix?","back":"Transpose the matrix, so [i, j] becomes [j, i]\n"},{"title":"card_820","front":"How can you find the shortest path on a DAG?","back":"1. Topological sort\n2. follow the topological sort, relaxing edges\n"},{"title":"card_821","front":"How to find the longest path on a weighted DAG?","back":"1. Set all edges to their negative weight.\n2. Topological sort \n3. follow the topological sort, relaxing edges\n"},{"title":"card_822","front":"What is the diameter of a graph?","back":"The shortest path of the farthest nodes. That is, it is the greatest distance between any pair of vertices. To find the diameter of a graph, first find the shortest path between each pair of vertices. The greatest length of any of these paths is the diameter of the graph.\n"},{"title":"card_823","front":"Under what condition can you not use Djikstra's algorithm?","back":"When the graph contains a negative edge. Can cause a cycle that will be traversed infinitely.\n"},{"title":"card_824","front":"In plain words, how does Kruskal's algorithm work?","back":"1. Create a set T and list for result\n2. Make a list of all edges in G\n3. Sort edges by weight, from least to greatest.\n4. Iterate edges in sorted order.\n5. For each edge, if u and v are not in T, add u and v to T, and add edge to result list.\n"},{"title":"card_825","front":"What can most dynamic programming problems be expressed as?","back":"Finding the shortest path in a DAG. Formulating it this way ensures you can solve it in linear or linearithmic time.\n"},{"title":"card_826","front":"What metric can you use to measure the badness of a line in a text justification problem?","back":"(page width - text width)^3\nMinimize the sum of the badness of the lines.\n"},{"title":"card_827","front":"How can you tell if a graph is 2-colorable?","back":"If it's bipartite. All trees are bipartite.\n"},{"title":"card_828","front":"What is it called when you have too many base cases in your recursion?","back":"arm's length recursion\n"},{"title":"card_829","front":"What is the base case of a recursion?","back":"The code required to give the solution to the smallest subproblem.\n"},{"title":"card_830","front":"What is the formula for n choose k?","back":"n! / k!(n - k)!\n"},{"title":"card_831","front":"What kinds of problems is dynamic programming best suited for?","back":"- optimizing left to right sequences (strings, tree nodes as array, permutations)\n- search all possibilities while storing results to avoid recomputing\n"},{"title":"card_832","front":"What is n choose n?","back":"1\n"},{"title":"card_833","front":"What is n choose 1?","back":"n\n"},{"title":"card_834","front":"What is n choose 0?","back":"1\n"},{"title":"card_835","front":"What is the Floyd-Warshall algorithm?","back":"The Floyd–Warshall algorithm is a dynamic programming algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles).\n"},{"title":"card_836","front":"What is the Bayes' rule (formula)?","back":"P(A|B) = (P(B|A) * P(A)) / P(B)\n"},{"title":"card_837","front":"How would you calculate P(A|B)?","back":"P(A and B) / P(B)\n"},{"title":"card_838","front":"How would you calculate P(A and B)?","back":"P(A) * P(B)\n"},{"title":"card_839","front":"How would you calculate P(A or B)?","back":"P(A) + P(B) - P(AB)\n"},{"title":"card_840","front":"What's another way to write P(A and B)?","back":"P(AB)\n"},{"title":"card_841","front":"What is a Markov chain?","back":"A Markov chain consists of states linked by transitions labeled with probabilities. The states do not have to be words. They could represent any state.\n"},{"title":"card_842","front":"Write a function that computes the sqrt(n) using binary search.","back":"How?\n"},{"title":"card_843","front":"What is P(A|A)?","back":"1\n"},{"title":"card_844","front":"At how many items should you expect a collision when hashing among n buckets?","back":"At sqrt(n) the probability is 1/2\n"},{"title":"card_845","front":"What is n/n^2?","back":"1/n\n"},{"title":"card_846","front":"What is the P( ! B ) ?","back":"1 - P(B)\n"},{"title":"card_847","front":"What is the probability of at least 1 H in 3 flips?","back":"1 - P(TTT) = 1 - 1/8 = 7/8\n"},{"title":"card_848","front":"With a fair coin, what is the probability of getting exactly 1 H in 4 flips?","back":"P(HTTT) + P(THTT) + P(TTHT) + P(TTTH) = 1/16 + 1/16 + 1/16 + 1/16 = 4/16 = 1/4\n"},{"title":"card_849","front":"With a fair coin, what is the probability of getting exactly k H in n flips?","back":"(n choose k)/2^n\n"},{"title":"card_850","front":"In what domain are most decision problems (P, Exp, R, outside R)?","back":"Outside R - they are uncomputable\n"},{"title":"card_851","front":"What does it mean when a problem is NP-Hard?","back":"It is as hard as any other problem in NP. A problem X is NP-Hard if every problem Y in NP-Hard reduces to X.\n"},{"title":"card_852","front":"What does it mean to reduce a problem A to a problem B?","back":"Converting the input to algorithm A into input into algorithm B, providing an answer for A.\n"},{"title":"card_853","front":"Is \"3-D matching\" NP-Complete?","back":"Yes\n"},{"title":"card_854","front":"Is \"triple coloring a graph\" NP-Complete?","back":"Yes\n"},{"title":"card_855","front":"Is \"two coloring a graph\" NP-Complete?","back":"No\n"},{"title":"card_856","front":"Is \"subset sum\" NP-Complete?","back":"Yes\n"},{"title":"card_857","front":"Is \"bin packing\" NP-Complete?","back":"Yes\n"},{"title":"card_858","front":"Is \"vertex cover\" NP-Complete?","back":"Yes\n"},{"title":"card_859","front":"Is \"set cover\" NP-Complete?","back":"Yes\n"},{"title":"card_860","front":"Name some NP-Complete problems.","back":"- tsp\n- knapsack problem (decision problem)\n- satisfiability\n- 3D matching\n- tricoloring\n- subset sum\n- rectangle packing\n- bin packing\n- vertex cover\n- set cover\n"},{"title":"card_861","front":"What is one way of doing approximate traveling salesman?","back":"Select a vertex as root.\nBuild a MST.\nDo a preorder traversal, store nodes in H.\nReturn H (a Hamiltonian cycle)\n"},{"title":"card_862","front":"What suffers from GC pauses?","back":"- long-running processes like servers\n- real-time applications like video processing\n"},{"title":"card_863","front":"How can an LRU cache be implemented with a linked list?","back":"When an item is accessed, it moves to the head of the list.\nThe trailing items can be overwritten with new items, or removed.\n"},{"title":"card_864","front":"How often are DRAM cells data rewritten?","back":"Every 10ms.\n"},{"title":"card_865","front":"What does Skylake architecture look like?","back":"Skylake: \n\nL1 Data cache = 32 KB, 64 B/line, 8-WAY. 64 cache lines per cache way\nL1 Instruction cache = 32 KB, 64 B/line, 8-WAY. 64 cache lines per cache way\nL2 cache = 256 KB, 64 B/line, 4-WAY\nL3 cache = 8 MB, 64 B/line, 16-WAY\n"},{"title":"card_866","front":"What is a TLB?","back":"A translation lookaside buffer (TLB) is a cache that memory management hardware uses to improve virtual address translation speed. The majority of desktop, laptop, and server processors includes one or more TLBs in the memory management hardware, and it is nearly always present in any hardware that utilizes paged or segmented virtual memory.\n"},{"title":"card_867","front":"In a direct mapped or set associative cache, what is special about the cache size?","back":"Main memory is divided into pages, and a memory page maps directly to the cache way size. So an item in a cache page can be mapped to any one of 8 cache ways in an 8-way associative cache. A direct mapped cache simply has one cache way, but it works the same way.\n"},{"title":"card_868","front":"How many bits does a SHA1 produce?","back":"160\n"},{"title":"card_869","front":"How many bits does a SHA2 and SHA3 produce?","back":"224 to 512\n"},{"title":"card_870","front":"Is it always letters we are looking for in compression?","back":"No. Hardly.\nWe are looking to compress discrete symbols, not letters. If we have a few words, they could be symbols.\nWe try to balance longest chains of symbols and the lowest entropy.\n"},{"title":"card_871","front":"What is Zopfli?","back":"Zopfli is data compression software that encodes data into DEFLATE, gzip and zlib formats. It achieves higher compression than other DEFLATE/zlib implementations, but takes much longer to perform the compression. It was first released in February 2013 by Google.\n"},{"title":"card_872","front":"What is the Chinese remainder theorem?","back":"If one knows the remainders of the division of an integer n by several integers, then one can determine uniquely the remainder of the division of n by the product of these integers, under the condition that the divisors are pairwise coprime.\n"},{"title":"card_873","front":"How do you change a 2s complement positive integer into a negative one?","back":"Flip all bits and + 1\n"},{"title":"card_874","front":"How do you change a 2s complement negative integer into a positive one?","back":"Flip all bits and + 1 (same as going the other way)\n"},{"title":"card_875","front":"Which way does the stack grow?","back":"Down to lower memory addresses.\n"},{"title":"card_876","front":"What is polymorphism in OO?","back":"A property of OO in which an abstraction operation may be performed in different ways in different classes, but share an interface.\nAlso can mean multiple methods of the same name but different signature.\n"},{"title":"card_877","front":"What are the 4 main tenets of OO?","back":"Abstraction\nPolymorphism\nInheritance \nEncapsulation\n\na pie (acronym)\n"},{"title":"card_878","front":"What is dynamic binding?","back":"Dynamic binding, also called dynamic dispatch, is the process of linking procedure call to a specific sequence of code (method) at run-time. Dynamic binding is also known as late binding or run-time binding. Dynamic binding is an object oriented programming concept and it is related with polymorphism and inheritance.\n"},{"title":"card_879","front":"What is a package?","back":"A group of classes bundled together.\n"},{"title":"card_880","front":"What is an interface in OO?","back":"Similar to an abstract data type, but simply defines the expected behaviors of a class, but does not suggest an implementation.\n"},{"title":"card_881","front":"What is a framework?","back":"A reusable piece of software that implements a generic solution to a generalized problem. It saves time by being a close model of the problem domain and can reach 100% with details coded by the implementer.\n"},{"title":"card_882","front":"What are hooks?","back":"The portions of a framework that are called, but do nothing and require implementation when needed.\n"},{"title":"card_883","front":"What is a server?","back":"A program that provides a service for other programs to connect to it.\n"},{"title":"card_884","front":"What is an OCL?","back":"Object constraint language. A specification language designed to formally specify constraints in software modules. An OCL expression specifies a logical fact about the system that must remain true.\n"},{"title":"card_885","front":"What is the Chain of Responsibility pattern?","back":"Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.\n"},{"title":"card_886","front":"What is the Command pattern?","back":"Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.\n"},{"title":"card_887","front":"What design pattern avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request?","back":"Chain of Responsibility\n"},{"title":"card_888","front":"What design pattern encapsulates a request as an object, thereby letting you parameterize clients with different requests?","back":"Command pattern\n"},{"title":"card_889","front":"What is the Interpreter pattern?","back":"Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.\n"},{"title":"card_890","front":"What design pattern, given a language, defines a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language?","back":"Interpreter pattern\n"},{"title":"card_891","front":"What is the Iterator pattern?","back":"Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.\n"},{"title":"card_892","front":"What design pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation?","back":"Iterator pattern\n"},{"title":"card_893","front":"What is the Mediator pattern?","back":"Defines an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly and it lets you vary their interactions independently.\n"},{"title":"card_894","front":"What design pattern defines an object that encapsulates how a set of objects interact?","back":"Mediator pattern\n"},{"title":"card_895","front":"What is the Memento pattern?","back":"Without violating encapsulation, capture and externalize an object's internal state so that the object can be restore to this state later.\n"},{"title":"card_896","front":"What design pattern captures and externalize an object's internal state so that the object can be restore to this state later?","back":"Memento pattern\n"},{"title":"card_897","front":"What is the Observer pattern?","back":"Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.\n"},{"title":"card_898","front":"What design pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically?","back":"Observer pattern\n"},{"title":"card_899","front":"What is the State pattern?","back":"Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.\n"},{"title":"card_900","front":"What design pattern allows an object to alter its behavior when its internal state changes?","back":"State pattern\n"},{"title":"card_901","front":"What is the Strategy pattern?","back":"Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Lets the algorithm vary independently from clients that use it.\n"},{"title":"card_902","front":"What design pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable, and lets the algorithm vary independently from clients that use it?","back":"Strategy pattern\n"},{"title":"card_903","front":"What is the Template Method pattern?","back":"Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.\n"},{"title":"card_904","front":"What design pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses?","back":"Template Method pattern\n"},{"title":"card_905","front":"What is the Visitor pattern?","back":"Represents an operation to be performed on the elements of an object structure. Lets you define a new operation without changing the classes of the elements on which it operates.\n"},{"title":"card_906","front":"What design pattern represents an operation to be performed on the elements of an object structure and lets you define a new operation without changing the classes of the elements on which it operates?","back":"Visitor pattern\n"},{"title":"card_907","front":"What is the Adapter pattern?","back":"Converts the interface of a class into another interface clients expect. Lets classes work together that couldn't otherwise because of incompatible interfaces.\n"},{"title":"card_908","front":"What design pattern converts the interface of a class into another interface clients expect?","back":"Adapter pattern\n"},{"title":"card_909","front":"What is the Bridge pattern?","back":"Decouples an abstraction from its implementation so that the two can vary independently.\n"},{"title":"card_910","front":"What design pattern decouples an abstraction from its implementation so that the two can vary independently?","back":"Bridge pattern\n"},{"title":"card_911","front":"What is the Composite pattern?","back":"Compose objects into tree structures to represent part-whole hierarchies. Lets clients treat individual objects and compositions of objects uniformly.\n"},{"title":"card_912","front":"What design pattern composes objects into tree structures to represent part-whole hierarchies?","back":"Composite pattern\n"},{"title":"card_913","front":"What is the Decorator pattern?","back":"Attaches additional responsibilities to an object dynamically. Provides a flexible alternative to sub-classing for extending functionality.\n"},{"title":"card_914","front":"What design pattern attaches additional responsibilities to an object dynamically and provides a flexible alternative to sub-classing for extending functionality?","back":"Decorator pattern\n"},{"title":"card_915","front":"What is the Facade pattern?","back":"Provides a unified interface to a set of interfaces in a subsystem. Defines a high-level interface that makes the subsystem easier to use.\n"},{"title":"card_916","front":"What design pattern provides a unified interface to a set of interfaces in a subsystem and defines a high-level interface that makes the subsystem easier to use.","back":"Facade pattern\n"},{"title":"card_917","front":"What is the Flyweight pattern?","back":"Uses sharing to support large numbers of fine-grained objects efficiently.\n"},{"title":"card_918","front":"What design pattern uses sharing to support large numbers of fine-grained objects efficiently?","back":"Flyweight pattern\n"},{"title":"card_919","front":"What is the Proxy pattern?","back":"Provides a surrogate or placeholder for another object to control access to it.\n"},{"title":"card_920","front":"What design pattern provides a surrogate or placeholder for another object to control access to it?","back":"Proxy pattern\n"},{"title":"card_921","front":"What is the Abstract Factory pattern?","back":"Provides an interface for creating families of related or dependent objects without specifying their concrete class.\n"},{"title":"card_922","front":"What design pattern provides an interface for creating families of related or dependent objects without specifying their concrete class?","back":"Abstract Factory pattern\n"},{"title":"card_923","front":"What is the Builder pattern?","back":"Separates the construction of a complex object from its representation, so the same construction process can create different representations.\n"},{"title":"card_924","front":"What design pattern separates the construction of a complex object from its representation, so the same construction process can create different representations?","back":"Builder pattern.\n"},{"title":"card_925","front":"What is the Factory Method pattern?","back":"(Technically it's an idiom)\nDefines an interface for creating an object, but lets subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses.\n"},{"title":"card_926","front":"What design pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate?","back":"Factory method (technically an idiom, not a design pattern)\n"},{"title":"card_927","front":"What is the Prototype pattern?","back":"Specifies the kinds of objects to create using a prototypical instance, and creates new objects by copying this prototype.\n"},{"title":"card_928","front":"What design pattern specifies the kinds of objects to create using a prototypical instance, and creates new objects by copying this prototype?","back":"Prototype pattern\n"},{"title":"card_929","front":"What is the Singleton pattern?","back":"Ensures a class only has one instance and provides a global point of access to it.\n"},{"title":"card_930","front":"What design pattern ensures a class only has one instance and provides a global point of access to it?","back":"Singleton pattern\n"},{"title":"card_931","front":"What are design patterns?","back":"Recurring, reusable solutions to common class and class relationship problems.\n"},{"title":"card_932","front":"What is the Law of Demeter?","back":"Each unit should have only limited knowledge about other units - only units \"closely\" related to the current unit. Each unit should only talk to friends, not strangers. Only talk to immediate friends.\n"},{"title":"card_933","front":"If a cache line size is 64B, and the memory bus is 64 bits wide, how many transfers per cache line?","back":"8\n"},{"title":"card_934","front":"What does an exclusive cache style?","back":"An eviction from L1D pushes the cache line down into L2, which has the same cache line size. Each eviction is progressively more expensive.\n"},{"title":"card_935","front":"What manufacturer uses an exclusive cache style?","back":"AMD\n"},{"title":"card_936","front":"How does an inclusive cache style work?","back":"Each cache line in L1D is also in L2. This makes L1D eviction faster.\n"},{"title":"card_937","front":"What manufacturer uses an inclusive cache style?","back":"Intel\n"},{"title":"card_938","front":"What is the Fast Fourier Transform?","back":"A fast Fourier transform (FFT) algorithm computes the discrete Fourier transform (DFT) of a sequence, or its inverse. Fourier analysis converts a signal from its original domain (often time or space) to a representation in the frequency domain and vice versa. An FFT rapidly computes such transformations by factorizing the DFT matrix into a product of sparse (mostly zero) factors.\n"},{"title":"card_939","front":"What is a skip list?","back":"A data structure that allows fast search within an ordered sequence of elements. Fast search is made possible by maintaining a linked hierarchy of subsequences, with each successive subsequence skipping over fewer elements than the previous one. Searching starts in the sparsest subsequence until two consecutive elements have been found, one smaller and one larger than or equal to the element searched for.\n\nA skip list is built in layers. The bottom layer is an ordinary ordered linked list. Each higher layer acts as an \"express lane\" for the lists below, where an element in layer i appears in layer i+1 with some fixed probability p (two commonly used values for p are 1/2 or 1/4).\n"},{"title":"card_940","front":"What operations does a skip list support and what is their avg and worst case times?","back":"search: O(log n) O(n)\ninsert: O(log n) O(n)\ndelete: O(log n) O(n)\n"},{"title":"card_941","front":"What operations does a van Emde Boas tree support and what are the time complexities?","back":"All are O(log log M), where M is the total number of items that can be stored = 2^m\nOr O(log m) where m is the actual number of items stored\nSpace: O(M)\n\nSearch\nInsert\nDelete\nPredecessor\nSuccessor\n"},{"title":"card_942","front":"What are the complexities for treap operations?","back":"For all the basic maintenance operations, they are O(log n) average case and O(n) worst case.\n- Search\n- Insert\n- Delete\n\nFor these operations, O(m log n/m) for treaps of sizes m and n, with m ≤ n. \n- union\n- intersection\n- difference\n"},{"title":"card_943","front":"What are Catalan numbers?","back":"Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects. They can be thought of as the set of balanced parentheses.\n"},{"title":"card_944","front":"What is Karatsuba multiplication?","back":"It reduces the multiplication of two n-digit numbers to at most n^1.585 single-digit multiplications in general (and exactly n^log(base2)3 when n is a power of 2). The Karatsuba algorithm was the first multiplication algorithm asymptotically faster than the quadratic \"grade school\" algorithm.\n"},{"title":"card_945","front":"What is the time complexity of Ford-Fulkerson?","back":"O(E max|f|)\n"},{"title":"card_946","front":"16^0 ?","back":"1\n"},{"title":"card_947","front":"16^1 ?","back":"16\n"},{"title":"card_948","front":"16^2 ?","back":"256\n"},{"title":"card_949","front":"16^3 ?","back":"4096\n"},{"title":"card_950","front":"16^4 ?","back":"65,536\n"},{"title":"card_951","front":"16^5 ?","back":"1,048,576\n"},{"title":"card_952","front":"16^6 ?","back":"16 million\n"},{"title":"card_953","front":"16^7","back":"268 million\n"},{"title":"card_954","front":"16^8 ?","back":"4.294 billion, same as 2^32\n"},{"title":"card_955","front":"What is 0xB in decimal?","back":"11\n"},{"title":"card_956","front":"What is 0xC in decimal?","back":"12\n"},{"title":"card_957","front":"What is 0xD in decimal?","back":"13\n"},{"title":"card_958","front":"What is 0xE in decimal?","back":"14\n"},{"title":"card_959","front":"What is 0xF in decimal?","back":"15\n"},{"title":"card_960","front":"What is 0xA in decimal?","back":"10\n"},{"title":"card_961","front":"What is 0xA in binary?","back":"1010\n"},{"title":"card_962","front":"What is 0xB in binary?","back":"1011\n"},{"title":"card_963","front":"What is 0xC in binary?","back":"1100\n"},{"title":"card_964","front":"What is 0xD in binary?","back":"1101\n"},{"title":"card_965","front":"What is 0xE in binary?","back":"1110\n"},{"title":"card_966","front":"What is 0xF in binary?","back":"1111\n"},{"title":"card_967","front":"How are the priorities of a treap assigned?","back":"Randomly generated upon insertion. That randomness is used to keep the tree balanced.\n"},{"title":"card_968","front":"Give an example of a proposition in conjunctive normal form.","back":"(A + ~B)(A + B)\n"},{"title":"card_969","front":"How does a half-adder handle an addition?","back":"XOR for the sum and AND for the carry\n"},{"title":"card_970","front":"Is a geometric Steiner tree NP-Complete?","back":"Yes\n"},{"title":"card_971","front":"What are the 2 algorithms for convex hull?","back":"- Graham scan\n- Jarvis march (gift-wrapping method)\n"},{"title":"card_972","front":"How does a Graham scan work in finding convex hull?","back":"At O(n log n), uses a sort and then a simple single pass of all the points, and making only left turns as it goes around the perimeter counter-clockwise. When the next point is a right turn, it backtracks past all points (using a stack and popping points off) until that turn turns into a left turn.\n"},{"title":"card_973","front":"How does the Jarvis march work in finding convex hull?","back":"Starting with the leftmost point p: \nGo through each point to the right of that point, and using p as a pivot, find which point is the most clockwise. O(n)\nGet the most clockwise point as the new p - O(1)\nLoop again with new p\n\nThis continues until the starting point is reached O(h) - where h is the number of hull points\n"},{"title":"card_974","front":"What is the worst case time complexity of a Jarvis march?","back":"O(n^2)\nOccurs when most points are part of the hull, and few points contained in the hull.\n"},{"title":"card_975","front":"What is the average complexity of a Jarvis march?","back":"O(n * h) where h is the number of points that compose the hull.\n"},{"title":"card_976","front":"What is white-box testing?","back":"The tester is using knowledge of the program's internals.\n"},{"title":"card_977","front":"What is black-box testing?","back":"The tester is testing without knowledge of the internals.\n"},{"title":"card_978","front":"What is unit testing?","back":"Testing a single module in isolation.\n"},{"title":"card_979","front":"What can affect testing, apart from API inputs?","back":"- timing of inputs\n- disk full\n- network latency\n- network failures\n"},{"title":"card_980","front":"What are 3 situations where timing of inputs is important in testing?","back":"- when SUT interacts directly with hardware devices\n- when SUT interfaces with other machines on the network\n- SUT is multithreaded\n"},{"title":"card_981","front":"What is a mock object?","back":"An object used to replicate the interfaces and interactions of a larger system that can be bolted on to the SUT.\n"},{"title":"card_982","front":"What is integration testing?","back":"Testing units together to ensure the integrated behavior performs as expected.\n"},{"title":"card_983","front":"What is system testing?","back":"- not concerned with internals\n- does system as a while perform acceptably for the important use cases\n"},{"title":"card_984","front":"What is differential testing?","back":"Running test inputs into 2 different implementations and then testing for equality. This is useful for testing multiple versions of the software.\n"},{"title":"card_985","front":"What is stress testing?","back":"Testing code or a system beyond its normal usage.\nTesting large inputs.\nTesting many requests.\n"},{"title":"card_986","front":"How can you tell you're testing enough?","back":"Code coverage metrics (of which there are a few)\n"},{"title":"card_987","front":"What does code coverage not tell you?","back":"- missing errors of omission\n- code that misses a specification item\n- does not tell us that code looped the correct number of times\n"},{"title":"card_988","front":"What should you do when you discover that not all code is covered?","back":"Don't blindly write tests to cover all cases.\nRethink the tests. Perhaps they are interpreting the functionality incorrectly.\n"},{"title":"card_989","front":"What are some coverage metrics?","back":"- line coverage\n- statement coverage (multiple statements on a line)\n- branch coverage\n- mc/dc coverage\n- loop coverage\n"},{"title":"card_990","front":"What is mc/dc coverage?","back":"modified condition / decision\n\n- Required for certain types of avionics software\n- Tests every possible branch and condition\n"},{"title":"card_991","front":"What is path coverage?","back":"Coverage that is concerned with the paths taken to arrive at a place in the code.\n"},{"title":"card_992","front":"What is infeasible code?","back":"Code that can never be true.\nInfeasible code is code that is either not forward- or not backward-reachable. Infeasible code is not necessarily an error but it is a good indicator that something is wrong with the code and, e.g., in avionics, infeasible code is forbidden by current standards.\n"},{"title":"card_993","front":"Should you include integration tests in code coverage metrics?","back":"No\n"},{"title":"card_994","front":"What should you do before fixing a reported bug?","back":"Write a test. Avoiding this practice allows bugs to re-appear.\n"},{"title":"card_995","front":"Why should tests be idempotent and isolated?","back":"It allows tests to be run in any order, re-run, and parallelized.\n"},{"title":"card_996","front":"delete (unordered singly linked list)","back":"O(n)\n"},{"title":"card_997","front":"find (unordered singly linked list)","back":"O(n)\n"},{"title":"card_998","front":"delete (ordered singly linked list)","back":"O(n)\n"},{"title":"card_999","front":"find (Binary Search Tree)","back":"O(h)\n"},{"title":"card_1000","front":"add (Binary Search Tree)","back":"O(h)\n"},{"title":"card_1001","front":"Add element to the top of the stack - push","back":"O(1)\n"},{"title":"card_1002","front":"Remove the top element of the stack - pop","back":"O(1)\n"},{"title":"card_1003","front":"Return the value of the top element of the stack without removing it.","back":"O(1)\n"},{"title":"card_1004","front":"Add an element to a queue.","back":"O(1)\n"},{"title":"card_1005","front":"Remove an element from the front of the queue. dequeue","back":"O(1)\n"},{"title":"card_1006","front":"Return the element from the front of the queue without removing it. - front","back":"O(1)\n"},{"title":"card_1007","front":"find (unordered array)","back":"O(n)\n"},{"title":"card_1008","front":"add (unordered array)","back":"O(1)\n"},{"title":"card_1009","front":"delete (unordered array)","back":"O(N)\n"},{"title":"card_1010","front":"find (sorted array)","back":"O(log n)\nbinary search\n"},{"title":"card_1011","front":"add (sorted array)","back":"O(n)\n"},{"title":"card_1012","front":"delete an element from a sorted array","back":"O(N)\n"},{"title":"card_1013","front":"find (unordered singly linked list)","back":"O(N)\n"},{"title":"card_1014","front":"add (unordered singly linked list)","back":"O(1)\n"},{"title":"card_1015","front":"delete (unordered singly linked list)","back":"O(N)\n"},{"title":"card_1016","front":"find (ordered singly linked list)","back":"O(N)\n"},{"title":"card_1017","front":"add (ordered singly linked list)","back":"O(N)\n"},{"title":"card_1018","front":"delete (ordered singly linked list)","back":"O(N)\n"},{"title":"card_1019","front":"find (Binary Search Tree)","back":"O(h)\n"},{"title":"card_1020","front":"add (Binary Search Tree)","back":"O(h)\n"},{"title":"card_1021","front":"delete (Binary Search Tree)","back":"O(h)\n"},{"title":"card_1022","front":"find (Balanced Binary Search Tree)","back":"O(log N)\n"},{"title":"card_1023","front":"add (Balanced Binary Search Tree)","back":"O(log N)\n"},{"title":"card_1024","front":"delete (Balanced Binary Search Tree)","back":"O(log N)\n"},{"title":"card_1025","front":"find (Balanced Binary Search Tree)","back":"O(log N)\n"},{"title":"card_1026","front":"add (Balanced Binary Search Tree)","back":"O(log N)\n"},{"title":"card_1027","front":"delete (Balanced Binary Search Tree)","back":"O(log N)\n"},{"title":"card_1028","front":"What is a skip list?","back":"A data structure for storing a sorted list of items using a hierarchy of linked lists that connect increasingly sparse subsequences of the items.\nO(log N) expected time for all operations, O(N) worst case.\n"},{"title":"card_1029","front":"What is a treap?","back":"Tree + heap\nA random priority is assigned to every key and must maintain two properties:\n- They are in order with respect to their keys, as in a typical binary search tree\n- They are in heap order with respect to their priorities, that is, no key has a key of lower priority as an ancestor\nO(log N) expected time for all operations, O(N) worst case.\n"},{"title":"card_1030","front":"What is a max-heap?","back":"A queue in which each element has a \"priority\" assigned to it. Elements with higher priorities are served before lower priorities.\n"},{"title":"card_1031","front":"min (unordered sequence)","back":"O(N)\n"},{"title":"card_1032","front":"insert (unordered sequence)","back":"O(1)\n"},{"title":"card_1033","front":"removeMin (unordered sequence)","back":"O(N)\n"},{"title":"card_1034","front":"min (ordered sequence)","back":"O(1)\n"},{"title":"card_1035","front":"insert (ordered sequence)","back":"O(N)\n"},{"title":"card_1036","front":"removeMin (ordered sequence)","back":"O(1)\n"},{"title":"card_1037","front":"build (ordered sequence)","back":"O(N log N)\n"},{"title":"card_1038","front":"min (binary heap)","back":"O(1)\n"},{"title":"card_1039","front":"insert (binary heap)","back":"O(log N)\n"},{"title":"card_1040","front":"removeMin (binary heap)","back":"O(log N)\n"},{"title":"card_1041","front":"build (binary heap)","back":"O(N)\n"},{"title":"card_1042","front":"What is a binary heap?","back":"A collection of keys arranged in a complete heap-ordered binary tree, represented in level order in an array (not using the first entry). The parent of the node in position k is in position [k/2] and the two children of the node in position k are in position 2k and 2k+1.\n"},{"title":"card_1043","front":"What is a Adaptable Priority Queue?","back":"A priority queue that allows you to change the priority of objects already in the queue.\n"},{"title":"card_1044","front":"What is the time complexity of quicksort?","back":"O(N^2 worst)\nO(N log N) - best & expected\n"},{"title":"card_1045","front":"Lower Bound for Comparison Based Sorting","back":"No comparison based sorting algorithm can be faster than O(N log N)\n"},{"title":"card_1046","front":"k-th smallest (full heap)","back":"Put all values in, do k removeMin operations: O(N + k log N)\n"},{"title":"card_1047","front":"What is a connected graph?","back":"There exists a path from every vertex to every other vertex in the graph.\n"},{"title":"card_1048","front":"What is a tree?","back":"An acyclic connected graph.\n"},{"title":"card_1049","front":"What is a cycle?","back":"Path with at least one edge whose first and last vertices are the same.\n"},{"title":"card_1050","front":"What is a spanning tree?","back":"A subgraph that contains all of that graph's vertices and a single tree.\n"},{"title":"card_1051","front":"Space required for an adjacency list","back":"O(E + V)\n"},{"title":"card_1052","front":"is_adjacent (u,v) (adjacency matrix)","back":"O(degree(u))\n"},{"title":"card_1053","front":"What is the complexity of an adjacency list DFS?","back":"O(E)\n"},{"title":"card_1054","front":"What is another name for a Min-Cost Spanning Tree?","back":"minimum spanning tree\n"},{"title":"card_1055","front":"Bitwise: Isolate the lowest bit that is 1 in x","back":"x & ~(x - 1)\n"},{"title":"card_1056","front":"Bitwise: Replace the lowest bit that is 1 with 0","back":"x & (x - 1)\n"},{"title":"card_1057","front":"Bitwise: Right propagate the rightmost set bit in x","back":"x | (x & ~(x - 1) - 1)\n"},{"title":"card_1058","front":"What are heuristics?","back":"Any approach to problem solving, learning, or discovery that employs a practical method not guaranteed to be optimal or perfect, but sufficient for the immediate goals. Where finding an optimal solution is impossible or impractical, heuristic methods can be used to speed up the process of finding a satisfactory solution. Heuristics can be mental shortcuts that ease the cognitive load of making a decision. Examples of this method include using a rule of thumb, an educated guess, an intuitive judgment, stereotyping, profiling, or common sense\n"},{"title":"card_1059","front":"What is stable sorting?","back":"Items with the same key are sorted based on their relative position in the original permutation\n"},{"title":"card_1060","front":"What is another name for a trie?","back":"Prefix tree or a radix tree.\n"},{"title":"card_1061","front":"What is internal sorting?","back":"An internal sort is any data sorting process that takes place entirely within the main memory of a computer. This is possible whenever the data to be sorted is small enough to all be held in the main memory. For sorting larger datasets, it may be necessary to hold only a chunk of data in memory at a time, since it won't all fit. The rest of the data is normally held on some larger, but slower medium, like a hard-disk. Any reading or writing of data to and from this slower media can slow the sortation process considerably.\n"},{"title":"card_1062","front":"What is external sorting?","back":"External sorting is a term for a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead they must reside in the slower external memory (usually a hard drive). External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are read, sorted, and written out to a temporary file. In the merge phase, the sorted subfiles are combined into a single larger file.\n\nMergesort is typically preferred.\n"},{"title":"card_1063","front":"What are 2 advantages of merge sort?","back":"- suitable for a linked list\n- suitable for external sort\n"},{"title":"card_1064","front":"What is disadvantages of merge sort?","back":"Need an extra buffer to hold the merged data\n"},{"title":"card_1065","front":"What are 3 advantages of heap sort?","back":"- don't need recursion\n- suitable for large data\n- locality of data\n"},{"title":"card_1066","front":"What is a disadvantage of heap sort?","back":"Usually slower than merge sort and quick sort.\n"},{"title":"card_1067","front":"What is a articulation vertex?","back":"The weakest point in a graph.\n"},{"title":"card_1068","front":"What is the chromatic number?","back":"The smallest number of colors needed for an edge coloring of a graph.\n"},{"title":"card_1069","front":"What are long-term issues involved in machine learning?","back":"- technical debt\n- lack of clear abstraction barriers \n- changing anything changes everything\n- feedback loop - usage based on your model changes the model\n- attractive nuisance (using a successful model in one domain where it doesn't fit in another)\n- non-stationarity - stick with current data, or get new, and how much of old data to reuse\n- tracking data dependencies - where did the data come from, how to get new data\n"},{"title":"card_1070","front":"How many rows are in a 12 x 16 matrix?","back":"12\n"},{"title":"card_1071","front":"How many columns are in a 12 x 16 matrix?","back":"16\n"},{"title":"card_1072","front":"In linear algebra a vector of 12 elements has how many rows?","back":"12\n"},{"title":"card_1073","front":"In linear algebra a vector of 12 elements has how many columns?","back":"1\n"},{"title":"card_1074","front":"In linear algebra a 12-dimensional vector has how many rows?","back":"12\n"},{"title":"card_1075","front":"In linear algebra a vector of 12-dimensional vector has how many columns?","back":"1\n"},{"title":"card_1076","front":"When multiplying a 4x3 matrix and a 3x6 matrix, what are the dimensions of the final matrix?","back":"4x6\n"},{"title":"card_1077","front":"Can you multiply a 3x2 and a 2x3 matrix?","back":"Yes\n"},{"title":"card_1078","front":"Can you multiply a 3x2 and a 3x2 matrix?","back":"No\n"},{"title":"card_1079","front":"Can you multiply a 3x2 and a 2x6 matrix?","back":"Yes\n"},{"title":"card_1080","front":"When multiplying a 5x2 matrix and a 2x5 matrix, what are the dimensions of the final matrix?","back":"5x5\n"},{"title":"card_1081","front":"Is matrix multiplication commutative? Does AxB = BxA?","back":"No.\n"},{"title":"card_1082","front":"Is matrix multiplication associative? Does (AxB)xC = Ax(BxC)?","back":"Yes\n"},{"title":"card_1083","front":"What would the identity matrix look like to multiply with an MxN matrix to get itself?","back":"An NxN matrix that is all zeroes except it has 1s on a top-left to bottom-right diagonal.\n"},{"title":"card_1084","front":"What must at least be true about a matrix for it to have an inverse?","back":"It must be square.\n"},{"title":"card_1085","front":"What does it mean to invert a matrix?","back":"Multiplying it by a specific matrix so that the product is the identity matrix.\n"},{"title":"card_1086","front":"What Python library computes the inverse of a matrix?","back":"numpy.linalg.inv\nor\nnumpy.linalg.pinv which can solve when the matrix is non-invertible\n"},{"title":"card_1087","front":"What are 2 words for matrices that are invertible?","back":"- singular\n- degenerate\n"},{"title":"card_1088","front":"If A is a matrix and Aij is the ith row, jth column, what is the traspose B?","back":"Bji\n"},{"title":"card_1089","front":"What is another name for quadratic?","back":"2nd-order polynomial\n"},{"title":"card_1090","front":"What is supervised learning?","back":"Supervised learning is the machine learning task of inferring a function from labeled training data. The training data consist of a set of training examples. In supervised learning, each example is a pair consisting of an input object (typically a vector) and a desired output value (also called the supervisory signal).\n"},{"title":"card_1091","front":"What is a regression problem?","back":"One that predicts a continuously valued output. May refer specifically to the estimation of continuous response variables, as opposed to the discrete response variables used in classification.\n"},{"title":"card_1092","front":"What is a classification problem?","back":"The problem of identifying to which of a set of categories (sub-populations) a new observation belongs, on the basis of a training set of data containing observations (or instances) whose category membership is known.\n"},{"title":"card_1093","front":"What is unsupervised learning?","back":"Unsupervised learning is the machine learning task of inferring a function to describe hidden structure from unlabeled data. Since the examples given to the learner are unlabeled, there is no error or reward signal to evaluate a potential solution. This distinguishes unsupervised learning from supervised learning and reinforcement learning.\n"},{"title":"card_1094","front":"What are the 2 types of problems that utilize supervised learning?","back":"Regression and classification\n"},{"title":"card_1095","front":"In machine learning, what is the symbol m used for?","back":"the number of training examples.\n"},{"title":"card_1096","front":"What is another term for linear regression with one variable?","back":"Univariate linear regression\n"},{"title":"card_1097","front":"What is gradient descent?","back":"Gradient descent is a first-order iterative optimization algorithm. To find a local minimum of a cost function using gradient descent, one takes steps proportional to the negative of the gradient (partial derivative or tangent) of the function at the current point.\n"},{"title":"card_1098","front":"What is it called when all training examples are used to calculate gradient descent?","back":"batch gradient descent\n"},{"title":"card_1099","front":"What is another term for linear regression with multiple variables?","back":"Multivariate linear regression\n"},{"title":"card_1100","front":"Why is feature scaling important?","back":"Without feature scaling, it can take gradient descent much longer to find the local minimum. The function may oscillate in small movements for much longer.\n"},{"title":"card_1101","front":"What is is good range to scale features down to?","back":"-1 to +1, or Ng's range: -3 to +3\n"},{"title":"card_1102","front":"What is mean normalization?","back":"A method of scaling a feature's values so that they all fall within a range relative to each other.\n"},{"title":"card_1103","front":"What is a good range for mean normalization?","back":"-0.5 to +0.5\n"},{"title":"card_1104","front":"How can you calculate mean normalization over a set of features?","back":"for each x: xi = (xi - avg(x)) / (max_x - min_x)\n\n(max_x - min_x) can be replaced with the standard deviation\n"},{"title":"card_1105","front":"Given a sufficiently small alpha, what can you expect from gradient descent?","back":"That it will eventually converge.\n"},{"title":"card_1106","front":"What does Andrew Ng use to find an appropriate alpha for gradient descent?","back":"0.001\n0.003\n0.01\n0.03\n0.1\n0.3\n1\n"},{"title":"card_1107","front":"How can you get your data to fit better using higher order terms in linear regression?","back":"You can take the data and square it, cube it, etc. \n\nx1 = (somevalue)^2\nx7 = (somevalue)^4\n\nThis is applied to data, not the function. The function still is theta1*x1 + theta2*x2, etc\n"},{"title":"card_1108","front":"What can affect invertibility in a matrix?","back":"- 2 more more features are linearly dependent or redundant (size in meters and size in ft) - remove redundant features\n- too few training examples (m) to features (n): m <= n (remove some features or use regularization)\n"},{"title":"card_1109","front":"When can we use the normal equation instead of gradient descent to minimize J(theta)?","back":"- when we have fewer than 10,000 features\n- have to ensure invertibility\n"},{"title":"card_1110","front":"What does numpy.allclose() do?","back":"Returns True if two arrays are element-wise equal within a tolerance.\n"},{"title":"card_1111","front":"Is feature scaling needed when using the normal equation?","back":"No\n"},{"title":"card_1112","front":"What is the normal equation?","back":"An equation that can minimize J(theta), solving for theta, instead of using gradient descent.\n\nAlso called ordinary least squares (OLS) or linear least squares, it's a method for estimating the unknown parameters in a linear regression model, with the goal of minimizing the sum of the squares of the differences between the observed responses in the given dataset and those predicted by a linear function of a set of explanatory variables.\n"},{"title":"card_1113","front":"What Python determines the pseudo-inverse of a matrix?","back":"numpy.linalg.pinv\n"},{"title":"card_1114","front":"What is treated as false in Python?","back":"• False\n• None\n• [] (an empty list)\n• {} (an empty dict)\n• \"\"\n• set()\n• 0\n• 0.0\n"},{"title":"card_1115","front":"What is a dot product?","back":"The dot product of two vectors is the sum of their componentwise products.\nv_1 * w_1 + ... + v_n * w_n\n"},{"title":"card_1116","front":"What is the quantile?","back":"The number at a given percentile of the data.\n"},{"title":"card_1117","front":"What is the mode?","back":"Most-common value(s) in a set of data. Could have more than one if there are 2 subsets with the same number of values.\n"},{"title":"card_1118","front":"What is dispersion?","back":"Dispersion refers to measures of how spread out our data is. Typically they’re statistics for which values near zero signify not spread out at all and for which large values (whatever that means) signify very spread out.\n"},{"title":"card_1119","front":"What is covariance?","back":"The mean value of the product of the deviations of two variates from their respective means.\n"},{"title":"card_1120","front":"What is a random variable?","back":"A random variable is a variable whose possible values have an associated probability distribution.\n\nA very simple random variable equals 1 if a coin flip turns up heads and 0 if the flip turns up tails. A more complicated one might measure the number of heads observed when flipping a coin 10 times or a value picked from range(10) where each number is equally likely.\n"},{"title":"card_1121","front":"What is PCA and what is it used for?","back":"Principal component analysis. We use it to extract one or more dimensions that capture as much of the variation in the data as possible.\n"},{"title":"card_1122","front":"What is a model?","back":"A specification of a mathematical (or probabilistic) relationship that exists between different variables.\n"},{"title":"card_1123","front":"What is machine learning?","back":"Creating and using models that are learned from data.\n"},{"title":"card_1124","front":"What is the degree of a vertex?","back":"The number of edges incident of the vertex, with loops counted twice.\n"},{"title":"card_1125","front":"What is quick select?","back":"A selection algorithm to find the kth smallest element in an unordered list. Quickselect uses the same overall approach as quicksort, choosing one element as a pivot and partitioning the data in two based on the pivot, accordingly as less than or greater than the pivot. However, instead of recursing into both sides, as in quicksort, quickselect only recurses into one side - the side with the element it is searching for. This reduces the average complexity from O(n log n) to O(n).\n"},{"title":"card_1126","front":"What is preemption?","back":"Preemption is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. Such a change is known as a context switch.\n"},{"title":"card_1127","front":"What is an inverted index?","back":"An index data structure storing a mapping from content, such as words or numbers, to its locations in a database file, or in a document or a set of documents (named in contrast to a Forward Index, which maps from documents to content). The purpose of an inverted index is to allow fast full text searches, at a cost of increased processing when a document is added to the database.\n"},{"title":"card_1128","front":"What is set partition?","back":"A partitioning of elements of some universal set into a collection of disjointed subsets. Thus, each element must be in exactly one subset.\n"},{"title":"card_1129","front":"What is a maximum spanning tree?","back":"A spanning tree of a weighted graph having maximum weight. It can be computed by negating the edges and running either Prim's or Kruskal's algorithms.\n"},{"title":"card_1130","front":"What is a minimum product spanning tree and when would you use it?","back":"The cost of a tree is the product of all the edge weights in the tree, instead of the sum of the weights. Since log(a*b) = log(a) + log(b), the minimum spanning tree on a graph whose edge weights are replaced with their logarithms gives the minimum product spanning tree on the original graph.\nYou would use it to minimize the product.\n"},{"title":"card_1131","front":"What is a rolling hash?","back":"A rolling hash (also known as a rolling checksum) is a hash function where the input is hashed in a window that moves through the input.\n\nOne of the main applications is the Rabin-Karp string search algorithm, which uses the rolling hash.\n"},{"title":"card_1132","front":"What is the Rabin-Karp algorithm?","back":"Compute hash codes of each substring whose length is the length of s, such as a function with the property that the hash code of a string is an additive function of each individual character. Get the hash code of a sliding window of characters and compare if the hash matches.\n"},{"title":"card_1133","front":"What is sharding?","back":"Sharding is a type of database partitioning that separates very large databases the into smaller, faster, more easily managed parts called data shards.\n"},{"title":"card_1134","front":"What is von Neumann Architecture?","back":"A model for modern computer organization created by John von Neumann, that had two main features:\n1) Both data & instructions are stored in the same place\n2) Units that store information are different from units that process information\n"},{"title":"card_1135","front":"What is the fetch-execute cycle?","back":"A 4 part system that describes how actions are performed in the CPU. There are 4 parts to this cycle:\n1) Fetch instructions\n2) Decode instructions\n3) Get data if needed\n4) Execute the instructions\n"},{"title":"card_1136","front":"What does a Control Unit (CU) do?","back":"Controls, organizes and deals with all the process and instruction the CPU receives. It is also in charge of the Fetch-Execute Cycle. Has two special purpose registers: the Instruction Register and the Program Counter.\n"},{"title":"card_1137","front":"What is the time complexity of breadth-first search?","back":"O(m + n) \nuses queue\n"},{"title":"card_1138","front":"What is the time complexity of breadth-first search?","back":"O(m + n) \nuses stack\n"},{"title":"card_1139","front":"What is the time and space complexity of minimum edit distance using dynamic programming?","back":"Time O(mn)\nSpace O(mn)\n"},{"title":"card_1140","front":"What is the time complexity of Floyd-Warshall?","back":"Theta(n^3)\n"},{"title":"card_1141","front":"What is the log of n! ?","back":"n log n\n"},{"title":"card_1142","front":"What is the time and space complexity of Bellman-Ford?","back":"Time : O (|V| |E|) or Theta(n^3) \nSpace: O (|V|)\n"},{"title":"card_1143","front":"What is the Bellman–Ford algorithm?","back":"An algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph. It is slower than Dijkstra's algorithm for the same problem, but more versatile, as it is capable of handling graphs in which some of the edge weights are negative numbers.\n"},{"title":"card_1144","front":"What is a Hamiltonian cycle?","back":"Given an undirected graph G = (V, E), does there exist a simple\ncycle Γ that contains every node in V ?\nCertificate is a permutation of the n nodes, contain each node in v exactly once, there is an edge btw each pair of adj nodes in the permutation.\n"},{"title":"card_1145","front":"What is the set cover problem?","back":"Given a set U of elements, a collection S1, S2, ..., Sm of subsets of\nU, and an integer k, does there exist a collection of ≤ k of these sets whose union is equal to U ?\n"},{"title":"card_1146","front":"What is the time and space complexity of heapsort?","back":"O(n lg n) time\nO(1) space\n"},{"title":"card_1147","front":"What is the time and space complexity of merge sort?","back":"O(n lg n) time\nO(n) space\n"},{"title":"card_1148","front":"How would you divide up a data set for training and testing?","back":"Split your data set, so that two-thirds of it is used to train the model, after which we test/measure the model’s performance on the remaining third.\n"},{"title":"card_1149","front":"How would you split up a data set in order to choose from multiple models?","back":"In such a situation, you should split the data into three parts: a training set for building models, a validation set for choosing among trained models (called the cross-validation set), and a test set for judging the final model.\n"},{"title":"card_1150","front":"What is a Type 1 error?","back":"A false positive\n"},{"title":"card_1151","front":"What is a Type 2 error?","back":"A false negative\n"},{"title":"card_1152","front":"In statistics, how would you calculate precision?","back":"true_pos / (true_pos + false_pos)\n"},{"title":"card_1153","front":"In statistics, how would you calculate recall?","back":"true_pos / (true_pos + false_neg)\n"},{"title":"card_1154","front":"In statistics, what does precision measure?","back":"Precision measures how accurate our positive predictions are.\n"},{"title":"card_1155","front":"In statistics, what does recall measure?","back":"Recall measures what fraction of the positives our model identified.\n"},{"title":"card_1156","front":"How would you calculate the F1 score?","back":"2 * precision * recall / (precision + recall)\n"},{"title":"card_1157","front":"What is another name for the F1 score?","back":"the harmonic mean of precision and recall\n"},{"title":"card_1158","front":"What is the trade-off between precision and recall?","back":"A model that predicts “yes” when it’s even a little bit confident will probably have a high recall but a low precision; a model that predicts “yes” only when it’s extremely confident is likely to have a low recall and a high precision.\n\nAlternatively, you can think of this as a trade-off between false positives and false negatives. Saying “yes” too often (high recall) will give you lots of false positives; saying “no” too often will give you lots of false negatives (high precision).\n"},{"title":"card_1159","front":"High bias and low variance typically correspond to _______.","back":"underfitting\n"},{"title":"card_1160","front":"Low bias but very high variance typically correspond to _______.","back":"overfitting\n"},{"title":"card_1161","front":"What can you do when your model has high bias (which means it performs poorly even on your training data)?","back":"One thing to try is adding more features.\n"},{"title":"card_1162","front":"What can you do if your model suffers from overfitting due to high variance?","back":"You can remove features. Another solution is to obtain more training examples (if you can).\nOr use regularization.\n"},{"title":"card_1163","front":"What does BFGS stand for?","back":"Broyden–Fletcher–Goldfarb–Shanno algorithm\n"},{"title":"card_1164","front":"What is L-BFGS?","back":"Limited-memory BFGS (L-BFGS or LM-BFGS) is an optimization algorithm in the family of quasi-Newton methods that approximates the Broyden–Fletcher–Goldfarb–Shanno (BFGS) algorithm using a limited amount of computer memory. It is a popular algorithm for parameter estimation in machine learning.\n"},{"title":"card_1165","front":"What are some alternative algorithms that can optimize for a logistic regression problem?","back":"- conjugate gradient\n- BGFS\n- L-BGFS\n"},{"title":"card_1166","front":"What makes neural networks superior over regression or classification?","back":"Each hidden layer learns its own features instead of being given features.\n"},{"title":"card_1167","front":"How should you initialize Theta for a neural network?","back":"Initialize as a matrix of random reals between 0 and 1. Constrain within a range of +/- epsilon using Theta * 2*epsilon - epsilon.\n"},{"title":"card_1168","front":"What are the number of neurons (units) at the input layer of a neural network?","back":"The number of features.\n"},{"title":"card_1169","front":"What are the number of neurons (units) at the output layer of a neural network performing classification?","back":"The number of classes you are classifying.\n"},{"title":"card_1170","front":"How many hidden layers should there be in a neural network?","back":"Start with 1 as a default, and if more than one, have the same number of units at each layer. The more the better. The number of units in each hidden layer should be more than, or a multiple of, the input units.\n"},{"title":"card_1171","front":"Machine learning: What tends to happen with the training error in a linear model as the degree of polynomial increases?","back":"The error decreases, but too high a degree of polynomial will cause overfitting.\n"},{"title":"card_1172","front":"Machine learning: What tends to happen with the cross-validation error in a linear model as the degree of polynomial increases?","back":"It starts high (high bias) and decreases, reaching a minimum, and then increases (high variance).\n"},{"title":"card_1173","front":"What command on the terminal will execute the previously run command?","back":"!!\n"},{"title":"card_1174","front":"What alias for ls -alF is included in Ubuntu's .bashrc?","back":"ll\n"},{"title":"card_1175","front":"How can you view your command line history?","back":"history\n"},{"title":"card_1176","front":"What command line tool allows you to search running processes by name?","back":"pgrep\n"},{"title":"card_1177","front":"What command line tool allows you to find and kill running processes by name?","back":"pkill\nkillall\n"},{"title":"card_1178","front":"What command line tool allows you to get the IP address from a domain name?","back":"dig\n"},{"title":"card_1179","front":"What command line tool allows you to see the internet connections between you and a given server IP or domain name?","back":"traceroute\n"},{"title":"card_1180","front":"What command line command allows you to display bandwidth usage on an interface by host?","back":"iftop -p -n\n"},{"title":"card_1181","front":"On the command line, how can you list all files beginning with a or f?","back":"ls [af]*\n"},{"title":"card_1182","front":"How can you tell what a given command line command is an alias for?","back":"type [command]\n"},{"title":"card_1183","front":"How can you create an alias for a command or set of commands?","back":"alias wowza='command 1; command 2; command 3'\n\nTo preserve it, add it to ~/.bashrc\n"},{"title":"card_1184","front":"How can you redirect errors form a command to a file?","back":"somecommand 2> errorfile.txt\n"},{"title":"card_1185","front":"How can you redirect stdout and errors from a command to a file?","back":"somecommand > somefile.txt 2>&1\n\nOR:\n\nsomecommand &> somefile.txt\n"},{"title":"card_1186","front":"How can you throw away errors from a command?","back":"somecommand 2> /dev/null\n"},{"title":"card_1187","front":"What command can you use with pipes to save to a file but continue piping to the next command?","back":"somecommand | tee file.txt | morecommand\n"},{"title":"card_1188","front":"How can you make multiple directories at once from the command line?","back":"mkdir {2009..2016}\n"},{"title":"card_1189","front":"How can you get a list of environment variables from the command line?","back":"printenv\n"},{"title":"card_1190","front":"What command can you use when your terminal is messed up by binary output?","back":"reset\n"},{"title":"card_1191","front":"How can you find out your computer's IP address from the command line?","back":"curl ifconfig.me\n"},{"title":"card_1192","front":"How can you get quick access to an ASCII table from the command line?","back":"man ascii\n"},{"title":"card_1193","front":"How do you show only repeated lines using uniq?","back":"uniq -d\n"},{"title":"card_1194","front":"What does sed stand for and what does it do?","back":"Stream editor. It does many things but is mainly used for search and replace.\n"},{"title":"card_1195","front":"Is there much difference between grep, egrep, and grep -P?","back":"Yes, grep doesn't support fancy regex.\negrep does extended\ngrep -P does perl-style but that's pretty close to egrep - can't see a difference\n"},{"title":"card_1196","front":"What can you use as a delimiter in sed?","back":"/, :, |, _ are all ok\n"},{"title":"card_1197","front":"What flag do you use with sed to turn on extended regular expressions?","back":"sed -r\n"},{"title":"card_1198","front":"What are the 4 parts of compiling a C program?","back":"- preprocessor\n- compiler - outputs assembly\n- assembler - outputs machine/object code\n- linked - links in dependent object files\n"},{"title":"card_1199","front":"What is the grep flag for line numbers?","back":"-n\n"},{"title":"card_1200","front":"What is the grep flag for showing matched portion only?","back":"-o\n"},{"title":"card_1201","front":"What command can you use to format in tab-stopped columns?","back":"column -t\n"},{"title":"card_1202","front":"How can you print the 1st, 2nd, and 4th columns in the /etc/passwd file that contain the word home?","back":"awk -F: '/home/ {print $1, $2, $4}' /etc/passwd\n"},{"title":"card_1203","front":"How can you print the 1st and 2nd column of a file only when the second column contains the word foo?","back":"awk '{ if($2 ~ /foo/) print $1,$2}' somefile\n"},{"title":"card_1204","front":"What is strace?","back":"strace is a diagnostic, debugging and instructional userspace utility for Linux. It is used to monitor interactions between processes and the Linux kernel, which include system calls, signal deliveries, and changes of process state. The operation of strace is made possible by the kernel feature known as ptrace.\n"},{"title":"card_1205","front":"What is tcpdump?","back":"tcpdump is the premier network analysis tool for information security professionals. Having a solid grasp of this über-powerful application is mandatory for anyone desiring a thorough understanding of TCP/IP.\n"},{"title":"card_1206","front":"What Linux command randomizes the lines of its input?","back":"shuf\n"},{"title":"card_1207","front":"How can we avoid deadlock?","back":"We can prevent deadlock by assigning an order to locks and require that the locks be acquired in that order. However, this approach is not often used in practice.\n"},{"title":"card_1208","front":"How can you tell if 2 rectangles do not overlap?","back":"The intersection of R1 and R2 will be a rectangle R3 whose bottom-left corner is at (max(x1, x3), max(y1, y3)) and top-right corner at (min(x2, x4), min(y2, y4)). If max(x1, x3) > min(x2, x4) or max(y1, y3) > min(y2, y4) then R3 does not exist, ie R1 and R2 do not intersect.\n"},{"title":"card_1209","front":"What happens to a class when you add __slots__?","back":"Space is saved because __dict__ is not created for each instance. __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.\nIf weak reference support is needed, then add '__weakref__' to the sequence of strings in the __slots__ declaration.\n"},{"title":"card_1210","front":"What happens when inheriting from a class without __slots__?","back":"When inheriting from a class without __slots__, the __dict__ attribute of that class will always be accessible, so a __slots__ definition in the subclass is meaningless.\n"},{"title":"card_1211","front":"If you use __slots__ on a class, what happens in subclasses?","back":"The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__ (which must only contain names of any additional slots).\n"},{"title":"card_1212","front":"How can you make a weak reference in Python?","back":"from weakref import ref r = ref(some_instance)\n"},{"title":"card_1213","front":"What 4 things should you check when given a debugging problem?","back":"- is the input valid and correct?\n- check that each line is correct and in the right order\n- check that the output is correct\n- check for common errors, and special cases for and algorithm or data structure\n"},{"title":"card_1214","front":"What determines the height of a tree?","back":"The height of a tree equals the height of its tallest subtree plus one.\nUse 1 + max(subtree1, subtree2)\n"},{"title":"card_1215","front":"What is Timsort?","back":"A hybrid stable sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.\nThe algorithm finds subsequences of the data that are already ordered, and uses that knowledge to sort the remainder more efficiently. This is done by merging an identified subsequence, called a run, with existing runs until certain criteria are fulfilled. Timsort has been Python's standard sorting algorithm since version 2.3.\n"},{"title":"card_1216","front":"What is concurrency?","back":"Running tasks at almost the same time in an unspecified order. This is achieved through context switches by the operating system.\n"},{"title":"card_1217","front":"What is a mutex?","back":"A mutually exclusive access to a resource. It's a special case of a semaphore with a maximum concurrency of 1.\n"},{"title":"card_1218","front":"What is busy waiting?","back":"Busy-waiting, busy-looping or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available.\n"},{"title":"card_1219","front":"How can you avoid busy waiting?","back":"Use Semaphore (Python, Java)\nUse Event (Python) or CountDownLatch (Java)\nsleep(0)\n"},{"title":"card_1220","front":"How can you reverse the words in a string with Python? Treat punctuation as part of the words.","back":"my_string.split()[::-1]\n"},{"title":"card_1221","front":"How can you convert a list to a string in Python?","back":"''.join(thelist)\n"},{"title":"card_1222","front":"Best case time complexity for selection sort?","back":"O(n^2)\n"},{"title":"card_1223","front":"Average case time complexity for selection sort?","back":"O(n^2)\n"},{"title":"card_1224","front":"Worst case time complexity for selection sort?","back":"O(n^2)\n"},{"title":"card_1225","front":"Best case time complexity for insertion sort?","back":"O(n) when data is already sorted or almost sorted.\n"},{"title":"card_1226","front":"Average case time complexity for insertion sort?","back":"O(n^2)\n"},{"title":"card_1227","front":"Worst case time complexity for insertion sort?","back":"O(n^2)\n"},{"title":"card_1228","front":"Worst case time complexity for quicksort?","back":"O(n^2) due to pathological pivot selection.\n"},{"title":"card_1229","front":"Average case time complexity for quicksort?","back":"O(n log n)\n"},{"title":"card_1230","front":"Best case time complexity for quicksort?","back":"O(n log n)\n"},{"title":"card_1231","front":"Best case time complexity for merge sort?","back":"O(n log n)\n"},{"title":"card_1232","front":"Worst case time complexity for quicksort?","back":"O(n log n)\n"},{"title":"card_1233","front":"Average case time complexity for quicksort?","back":"O(n log n)\n"},{"title":"card_1234","front":"What should you do when you have one or more lists that are sorted and you need to combine them into a sorted list?","back":"Merge step of merge sort.\n"},{"title":"card_1235","front":"What sort can you use when you have data you want to sort and the comparisons of keys are cheap but moving the data is expensive?","back":"Selection sort guarantees no more than n - 1 swaps.\n"},{"title":"card_1236","front":"What kind of sort can you use when the data is guaranteed to have no duplicates and needs to be done in-place?","back":"An unstable, in-place sort like quicksort.\n"},{"title":"card_1237","front":"What can you use to merge an unsorted list into an already sorted list?","back":"If the new list is short, insertion sort would be O(n).\nIf both lists are long, sort the short list and then do a merge.\n"},{"title":"card_1238","front":"How can you sort a list of Employee objects by surname then given_name, case-sensitive?","back":"sorted_firstnames = sorted(directory, key=lambda emp: emp.given_name.lower())\npprint(sorted(sorted_firstnames, key=lambda emp: emp.surname.lower()))\n"},{"title":"card_1239","front":"How can you sort a list of Employee objects by surname then given_name, but case-insensitive?","back":"import operator\n\npprint(sorted(directory, key=operator.attrgetter('surname', 'given_name')))\n"},{"title":"card_1240","front":"What should you know about the cmp argument in sort/sorted?","back":"In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. \n\nThe cmp argument was removed in 3.0.\n\nUse functools.cmp_to_key() to convert an old-style cmp function to a key function.\n"},{"title":"card_1241","front":"How can you get a stable sort using an unstable sorting algorithm?","back":"Add a sequence number to the data elements, like adding a new sequence property to the objects to be sorted.\n\nIn your comparator, if the compared keys are equal (difference is 0), break ties by returning e1.sequence - e2.sequence\n"},{"title":"card_1242","front":"What is a shortcut for calculating the Hamming distance?","back":"The Hamming distance of two words A and B can be calculated as the Hamming weight of A xor B.\n"},{"title":"card_1243","front":"What are green threads?","back":"- implemented by a virtual machine\n- faster but cannot take advantage of multiple cores\n- going away due to prevalence of multicore machines\n"},{"title":"card_1244","front":"What is preemptive threading?","back":"The OS swaps threads based on timing or other interrupts.\n"},{"title":"card_1245","front":"What is the thread cooperative model?","back":"Requires a thread to take some action (sleep, yield) and let other threads run.\n"},{"title":"card_1246","front":"How can an event-driven handler manage a long-running process, like waiting for a network response?","back":"Spawn a thread to call the network resource. Then queue the result once complete so the parent process (or main event thread) can respond and access the data without polling.\n"},{"title":"card_1247","front":"What is a monitor?","back":"A monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true. Monitors also have a mechanism for signalling other threads that their condition has been met. A monitor consists of a mutex (lock) object and condition variables. Monitors provide a mechanism for threads to temporarily give up exclusive access in order to wait for some condition to be met, before regaining exclusive access and resuming their task.\n"},{"title":"card_1248","front":"What is a spinlock?","back":"A form of busy waiting, that waits in a loop and repeatedly checks if a lock is available.\n"},{"title":"card_1249","front":"How do you solve the Dining Philosophers problem?","back":"- critical section is picking up one fork, second fork, and then eating then putting down forks.\n- one philosopher should pick up fork 2 then fork 1. if (i == 0) swap fork 1 and 2\n- one will get to eat more, the one to left of 0\n- to even it out, just change order in which each picks up: if (i % 2 == 0) swap fork 1 and 2\n"},{"title":"card_1250","front":"How are interfaces handled in Python?","back":"There are none.\nJust use duck typing.\nUse multiple inheritance: make an ABC and inherit\n"},{"title":"card_1251","front":"What should you do to make a Singleton thread-safe?","back":"It's best to make getInstance() thread-safe, or make generating the instance thread-safe so getInstance does not suffer from thread-safety overhead each time it's called.\n"},{"title":"card_1252","front":"What does ACID stand for?","back":"Atomicity\nConsistency\nIsolation\nDurability\n"},{"title":"card_1253","front":"What are some differences between C++ and Java?","back":"C++:\n- programmer control with low-level access\n- backwards compatibility with C\n- multiple inheritance\n- pass by value\n\nJava:\n- security\n- portability\n- runs in a VM, compiles to bytecode\n- JIT speeds it up considerably\n- garbage collection\n- single inheritance (multiple inheritance simulated by using interfaces)\n- pass by reference\n"},{"title":"card_1254","front":"What is the difference between a pointer and a reference?","back":"- must dereference a pointer: foo->prop\n- pointer can be null, a reference cannot\n- deal with reference as if it was declared in the same scope: foo.prop\n"},{"title":"card_1255","front":"Difference between inline functions and macros?","back":"Each reduces overhead of function calls at the expense of program size\n\nMacro:\n- text replacement by preprocessor\n- single line only\n- unexpected side effects if not careful\n\nInline:\n- replaces the call to an inline function with that function's body\n- ok for multiple lines\n- increases size, cuts down on overhead of repetitive function calls\n"},{"title":"card_1256","front":"What are the pros and cons of garbage collection?","back":"Good:\n- no dangling pointers\n- no double allocation\n- no memory leaks\n\nBad:\n- can over-allocate memory\n- stop and copy can cause pauses at inopportune times\n- slower performance\n- rapid development\n- circular references\n"},{"title":"card_1257","front":"What is a tracing garbage collector?","back":"Mark and sweep: pauses execution in order to mark all objects referenced by any thread of the program.\n"},{"title":"card_1258","front":"What is tri-color marking?","back":"Because of these performance problems, most modern tracing (mark and sweep) garbage collectors implement some variant of the tri-color marking abstraction. This avoids the execution pause common to mark and sweep.\n\nThree sets are created – white, black and gray:\n\n- The white set, or condemned set, is the set of objects that are candidates for having their memory recycled.\n- The black set is the set of objects that can be shown to have no outgoing references to objects in the white set, and to be reachable from the roots. Objects in the black set are not candidates for collection.\n- The gray set contains all objects reachable from the roots but yet to be scanned for references to \"white\" objects. Since they are known to be reachable from the roots, they cannot be garbage-collected and will end up in the black set after being scanned.\n"},{"title":"card_1259","front":"What are the difference between 32-bit and 64-bit applications?","back":"32-bit:\n- 32-bit memory addresses and registers\n\n64-bit:\n- 64-bit memory addressed and registers\n- requires 64-bit processor, 64-bit OS\n- can run 32-bit programs in compatibility mode\n- pointers require 64 bits so they take more space\n- fewer items fit in cache\n- x86-64 in 64-bit has an additional 8 additional general purpose registers\n"},{"title":"card_1260","front":"How can you transpose a matrix in a matrix?","back":"Label each row and column with row and column number. Sort by column, then by row.\n"},{"title":"card_1261","front":"How can you rotate an array of size n by k positions?","back":"Reverse 0 to k - 1, reverse k to end. Then reverse it all.\n"},{"title":"card_1262","front":"What is memory-mapping?","back":"Memory-mapping a file uses the operating system virtual memory system to access the data on the file system directly, instead of using normal I/O functions. Memory-mapping typically improves I/O performance because it does not involve a separate system call for each access and it does not require copying data between buffers – the memory is accessed directly by both the kernel and the user application.\n"},{"title":"card_1263","front":"What can you use to compute all-pairs shortest-paths?","back":"scipy.sparse.csgraph.floyd_warshall\n"},{"title":"card_1264","front":"How do you represent infinity in Python?","back":"float('Inf')\n"},{"title":"card_1265","front":"How do you represent negative infinity in Python?","back":"-float('Inf')\n"},{"title":"card_1266","front":"What is bcrypt?","back":"bcrypt is a password hashing function based on the Blowfish cipher. Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.\n"},{"title":"card_1267","front":"What is the relationship to false positives/negatives with a Bloom filter?","back":"False negatives are not possible.\nFalse positives are possible.\n"},{"title":"card_1268","front":"What algorithm is used for locality-sensitive hashing?","back":"simhash\n"},{"title":"card_1269","front":"What are 2 examples of probabilistic data structures?","back":"Bloom filter\nHyperLogLog\n"},{"title":"card_1270","front":"What can you use to solve linear programming problems in Python?","back":"numpy.linalg.solve()\n"},{"title":"card_1271","front":"What are 3 properties of good hashing functions?","back":"- minimize collisions\n- produces a good distribution\n- hashes consistently\n"},{"title":"card_1272","front":"What are 3 good uses of hash tables?","back":"- quick lookups, inserts, and deletes\n- removing duplicates\n- caching\n"},{"title":"card_1273","front":"If this exists, you can't use Dijkstra.","back":"A negative-weight edge.\n"},{"title":"card_1274","front":"How can you solve a set cover problem?","back":"- pick largest set that covers most of the uncovered spots\n- add it to covering set\n- then next largest, even if overlap\n\nO(n^2)\ngreedy but it works\n"},{"title":"card_1275","front":"When using k-nearest neighbors, what k should be used for size of points n?","back":"sqrt(n)\n"},{"title":"card_1276","front":"What is a suffix array?","back":"A suffix array is a sorted array of all suffixes of a string.\n\nThe suffix array of a string can be used as an index to quickly locate every occurrence of a substring pattern P within the string S. Finding every occurrence of the pattern is equivalent to finding every suffix that begins with the substring. Thanks to the lexicographical ordering, these suffixes will be grouped together in the suffix array and can be found efficiently with two binary searches. The first search locates the starting position of the interval, and the second one determines the end position.\n"},{"title":"card_1277","front":"Is knapsack problem NP-complete?","back":"The decision problem form of the knapsack problem (Can a value of at least V be achieved without exceeding the weight W?) is NP-complete, thus there is no known algorithm both correct and fast (polynomial-time) on all cases.\n\nThere is a pseudo-polynomial time algorithm using dynamic programming.\n"},{"title":"card_1278","front":"What is a hard problem that is not in NP?","back":"Two-player games such as chess provide examples of problems that are not in NP. \nThe only way to check if a move would eventually win the game is to construct the full tree of all your possible moves with his irrefutable replies and demonstrate that you, in fact, cannot win from the current position. This full tree will have a number of nodes exponential in its height, which is the number of moves before you lose playing your most spirited possible defense.\n\nThis tree cannot be constructed and analyzed in polynomial time, so the problem is not in NP.\n"},{"title":"card_1279","front":"Maintaining a sorted array is good for what type of operations?","back":"A sorted array will be appropriate if and only if there are not many insertions or deletions.\n"},{"title":"card_1280","front":"Why are Fibonacci heaps special?","back":"Fibonacci heaps support insert and decrease-key operations in constant amortized time, with O(lg n) amortized time extract-min and delete operations.\n"},{"title":"card_1281","front":"What makes van Emde Boas trees special?","back":"Van Emde Boas priority queues support O(lg lg n) insertion, deletion, search, max, and min operations where each key is an element from 1 to n.\n"},{"title":"card_1282","front":"Why is an adjacency list for the best choice for a planar graph?","back":"Planar graphs are always sparse, since any n-vertex planar graph can have at most 3n − 6 edges. Thus they should be represented using adjacency lists.\n"},{"title":"card_1283","front":"What can you do to save space in an adjacency matrix?","back":"Pack all of the ones and zeros into a series of bit vectors.\n"},{"title":"card_1284","front":"Can you use when your graph is extremely large?","back":"If your graph is extremely large, it may become necessary to switch to a hierarcchical representation, where the vertices are clustered into subgraphs that are compressed into single vertices. Two approaches exist to construct such a hierar-chical decomposition. The first breaks the graph into components in a natural or application-specific way. For example, a graph of roads and cities suggests a natural decomposition—partition the map into districts, towns, counties, and states.\n"},{"title":"card_1285","front":"Is bandwidth minimization NP-Complete?","back":"Yes. It stays NP-complete even if the input graph is a tree whose maximum vertex degree is 3, which is about as strong a condition as I have seen on any problem. Thus our only options are a brute-force search and heuristics.\n"},{"title":"card_1286","front":"Using an adjacency matrix how can you see how many paths exist between two points of length K?","back":"Matrix multiplication has a particularly interesting interpretation. Now consider the square of this matrix, A^2 = A × A. If A^2[i, j] ≥ 1. This means that there must be a vertex k such that A[i, k] = A[k, j] = 1, so i to k to j is a path of length 2 in G. More generally, A^k[i, j] counts the number of paths of length exactly k between i and j. This count includes nonsimple paths, where vertices are repeated, such as i to k to i to j.\n"},{"title":"card_1287","front":"What does it mean if the determinant of a matrix is zero?","back":"It is not invertible.\n"},{"title":"card_1288","front":"What does #P-complete mean?","back":"#P is the class of problems solvable on a “counting” machine in polynomial time. A counting machine returns the number of distinct solutions to a problem. Counting the number of Hamiltonian cycles in a graph is a #P-complete problem that is trivially NP-hard (and presumably harder), since any count greater than zero proves that the graph is Hamiltonian. Counting problems can be #P-complete even if the corresponding decision problem can be solved in polynomial time, as shown by the permanent and perfect matchings.\n"},{"title":"card_1289","front":"What can be said of integer programming in and NP-completeness?","back":"NP-complete to solve integer or mixed programs to optimality. However, there are integer programming techniques that work reasonably well in practice.\n"},{"title":"card_1290","front":"How can you convert a linear programming maximization problem into a minimization problem?","back":"To convert a maximization problem to a minimization one, simply multiply each coefficient of the objective function by −1. The remaining problems can be solved by adding slack variables to the model. See any textbook on linear programming for details\n"},{"title":"card_1291","front":"What is NC?","back":"NC (Nick's class) can be thought of as the problems that can be efficiently solved on a parallel computer. NC is a subset of P because polylogarithmic parallel computations can be simulated by polynomial-time sequential ones.\n"},{"title":"card_1292","front":"What is P-Complete?","back":"A decision problem is P-complete (complete for the complexity class P) if it is in P and every problem in P can be reduced to it by an appropriate reduction.\n"},{"title":"card_1293","front":"What is the Mersenne twister?","back":"Mersenne twister is a fast random number generator of period 2^19937 − 1.\n"},{"title":"card_1294","front":"Why is periodicity important in random rumber generation?","back":"The period defines how long a random number generator will generate numbers before it repeats the sequence. \nThe period of a PRNG is defined thus: the maximum, over all starting states, of the length of the repetition-free prefix of the sequence. The period is bounded by the number of the states, usually measured in bits. However, since the length of the period potentially doubles with each bit of \"state\" added, it is easy to build PRNGs with periods long enough for many practical applications.\n"},{"title":"card_1295","front":"What are Carmichael numbers?","back":"Carmichael numbers are composite integers that always satisfy Fermat's little theorem. They are pseudo-primes.\n"},{"title":"card_1296","front":"What is a convolution?","back":"A convolution is a mathematical operation on two functions (f and g); it produces a third function, that is typically viewed as a modified version of one of the original functions.\n"},{"title":"card_1297","front":"What is in mathematical application of FFT?","back":"FFT-based algorithm that multiplies two n-bit numbers in O(n lg n lg lg n) time is due to Schonhagen and Strassen.\n"},{"title":"card_1298","front":"How can you sort extremely large amount of data on disk with limited memory?","back":"The simplest approach to external sorting loads the data into a B-tree and then does an in-order traversal of the tree to read the keys off in sorted order. Real high-performance sorting algorithms are based on multiway-mergesort. Files containing portions of the data are sorted into runs using a fast internal sort, and then files with these sorted runs are merged in stages using 2- or k-way merging. Complicated merging patterns and buffer management based on the properties of the external storage device can be used to optimize performance.\n"},{"title":"card_1299","front":"How can you optimize quicksort?","back":"• Use randomization – randomly permute the keys before sorting.\n• Median of three – For your pivot element, use the median of the first, last, and middle elements of the array. \n• Leave small subarrays for insertion sort – Terminating the quicksort recursion and switching to insertion sort makes sense when the subarrays get small, say fewer than 20 elements.\n• Do the smaller partition first – Assuming that your compiler is smart enough to remove tail recursion.\n"},{"title":"card_1300","front":"What is a radix?","back":"The base, or radix, is the value that we raise to successive powers for each digit to the left of the radix point (note that the term decimal point only applies to decimal numbers).\n"},{"title":"card_1301","front":"16 * 2?","back":"32\n"},{"title":"card_1302","front":"16 * 3?","back":"48\n"},{"title":"card_1303","front":"16 * 4?","back":"64\n"},{"title":"card_1304","front":"16 * 5?","back":"80\n"},{"title":"card_1305","front":"16 * 6?","back":"96\n"},{"title":"card_1306","front":"16 * 7?","back":"112\n"},{"title":"card_1307","front":"16 * 8?","back":"128\n"},{"title":"card_1308","front":"16 * 9?","back":"144\n"},{"title":"card_1309","front":"16 * 10?","back":"160\n"},{"title":"card_1310","front":"16 * 16?","back":"256\n"},{"title":"card_1311","front":"16 * 11?","back":"176\n"},{"title":"card_1312","front":"16 * 12?","back":"192\n"},{"title":"card_1313","front":"16 * 13?","back":"208\n"},{"title":"card_1314","front":"16 * 14?","back":"224\n"},{"title":"card_1315","front":"16 * 15?","back":"240\n"},{"title":"card_1316","front":"What is the standard Intel 80x86 word size?","back":"16 bits\n"},{"title":"card_1317","front":"What is a weakly connected graph?","back":"A directed graph is weakly connected if it would be connected by ignoring the direction of edges. Thus, a weakly connected graph consists of a single piece. A directed graph is strongly connected if there is a directed path between every pair of vertices. This distinction is best made clear by considering the network of one- and two-way streets in any city. The network is strongly connected if it is possible to drive legally between every two positions. The network is weakly connected when it is possible to drive legally or illegally between every two positions. The network is disconnected if there is no possible way to drive from a to b.\n"},{"title":"card_1318","front":"How can you tell if a graph is a tree?","back":"Depth-first search can be used to test whether it is connected. If the graph is connected and has n − 1 edges for n vertices, it is a tree.\n"},{"title":"card_1319","front":"What kind of graph do you have to have in order to perform a topological sort?","back":"Only DAGs can be topologically sorted, since any directed cycle provides an inherent contradiction to a linear order of tasks.\n"},{"title":"card_1320","front":"What is important about every DAG?","back":"Every DAG can be topologically sorted, so there must always be at least one schedule for any reasonable precedence constraints among jobs.\n"},{"title":"card_1321","front":"How can you topologically sort a DAG?","back":"Ordering the vertices in terms of decreasing DFS finishing time.\n"},{"title":"card_1322","front":"What can you say about the number of possible topological sorts on a graph?","back":"The problem of counting the number of linear extensions (the number of ways to order a topological sort) is NP-hard.\n"},{"title":"card_1323","front":"In removing edges in order to make a graph acyclic, is this a hard problem?","back":"Removing the minimum number of edges in order to make a graph acyclic so that you can topological sort is NP complete.\n"},{"title":"card_1324","front":"Which is better: Prim's algorithm or Kruskal's algorithm?","back":"Prim's algorithm runs in O(n^2), while Kruskal's algorithm takes O(m log m) time. Thus Prim's algorithm is faster on dense graphs, while Kruskal's is faster on sparse graphs.\n"},{"title":"card_1325","front":"How can you find shortest path in an undirected graph?","back":"If your graph is unweighted, a simple breadth-first search starting from the source vertex will find the shortest path to all other vertices in linear time.\n"},{"title":"card_1326","front":"How can you find shortest paths on a DAG?","back":"Shortest paths in directed acyclic graphs can be found in linear time. Perform a topological sort to order the vertices such that all edges go from left to right starting from source s.\n"},{"title":"card_1327","front":"How can you find the shortest simple cycle?","back":"To find the shortest simple cycle, the easiest approach is to compute the lengths of the shortest paths from i to all other vertices, and then explicitly check whether there is an acceptable edge from each vertex back to i.\n"},{"title":"card_1328","front":"How can you find the longest cycle in a graph?","back":"Finding the longest cycle in a graph includes Hamiltonian cycle as a special case, so it is NP-complete.\n"},{"title":"card_1329","front":"How does preprocessing affect A* times?","back":"Goldberg, Kaplan, and Werneck describe an implementation of A∗ capable of answering point-to-point queries in one millisecond on national-scale road networks after two hours of preprocessing.\n"},{"title":"card_1330","front":"What is transitive closure and how is it recorded?","back":"Transitive closure can be thought of as establishing a data structure that makes it possible to solve reachability questions (can I get to x from y?) efficiently. After constructing the transitive closure, all reachability queries can be answered in constant time by simply reporting the appropriate matrix entry.\n"},{"title":"card_1331","front":"What is transitive reduction?","back":"Transitive reduction (also known as minimum equivalent digraph) is the inverse operation of transitive closure, namely reducing the number of edges while maintaining identical reachability properties. The transitive closure of G is identical to the transitive closure of the transitive reduction of G.\n"},{"title":"card_1332","front":"How can you tell if an undirected graph contains a Eulerian cycle?","back":"An undirected graph contains an Eulerian cycle iff \n(1) it is connected, and \n(2) each vertex is of even degree.\n"},{"title":"card_1333","front":"How can you tell if an undirected graph contains an Eulerian path?","back":"An undirected graph contains an Eulerian path iff \n(1) it is connected, and \n(2) all but two vertices are of even degree. These two vertices will be the start and end points of any path.\n"},{"title":"card_1334","front":"How can you determine if a directed graph contains an Eulerian cycle?","back":"A directed graph contains an Eulerian cycle iff (1) it is strongly-connected, and (2) each vertex has the same in-degree as out-degree.\n"},{"title":"card_1335","front":"How can you tell if a directed graph contains a Eulerian path?","back":"A directed graph contains an Eulerian path from x to y iff \n(1) it is connected, and \n(2) all other vertices have the same in-degree as out-degree, with x and y being vertices with in-degree one less and one more than their out-degrees, respectively.\n"},{"title":"card_1336","front":"What is the importance of minimum vertex degree?","back":"The minimum vertex degree is an upper bound for both edge and vertex connectivity, since deleting all its neighbors (or cutting the edges to all its neighbors) disconnects the graph into one big and one single-vertex component.\n"},{"title":"card_1337","front":"What does a biconnected graph mean?","back":"We say that G is biconnected if no single vertex deletion is sufficient to disconnect G. Any vertex that is such a weak point is called an articulation vertex. A bridge is the analogous concept for edges, meaning a single edge whose deletion disconnects the graph.\n"},{"title":"card_1338","front":"What is the relation of maximum flow and minimum cut?","back":"The maximum flow between vi, vj in G is exactly the weight of the smallest set of edges to disconnect vi from vj.\n"},{"title":"card_1339","front":"What is one heuristic to draw \"nice\" graphs for a given graph?","back":"As a first quick and dirty drawing, I recommend simply spacing the vertices evenly on a circle, and then drawing the edges as straight lines between vertices. Such drawings are easy to program and fast to construct. They have the substantial advantage that no two edges will obscure each other, since no three vertices will be collinear. Such artifacts can be hard to avoid as soon as you allow internal vertices into your drawing. An unexpected pleasure with circular drawings is the symmetry sometimes revealed because vertices appear in the order they were inserted into the graph. Simulated annealing can be used to permute the circular vertex order to minimize crossings or edge length, and thus significantly improve the drawing. A good, general purpose graph-drawing heuristic models the graph as a system of springs and then uses energy minimization to space the vertices. Let adjacent vertices attract each other with a force proportional to (say) the logarithm of their separation, while all nonadjacent vertices repel each other with a force proportional to their separation distance. These weights provide incentive for all edges to be as short as possible, while spreading the vertices apart. The behavior of such a system can be approximated by determining the force acting on each vertex at a particular time and then moving each vertex a small amount in the appropriate direction. After several such iterations, the system should stabilize on a reasonable drawing.\n"},{"title":"card_1340","front":"Is finding a maximum clique NP-Complete?","back":"Yes.\n"},{"title":"card_1341","front":"What is the max clique size for a planar graph?","back":"Planar graphs cannot have cliques of a size larger than four, or else they cease to be planar.\n"},{"title":"card_1342","front":"What is branch and bound?","back":"It usually of the form of a decision tree where each decision is represented by an edge. The leaves of this tree is the set of all possible solutions. To find the most optimized solution(i.e. one of the leaves) the following is the basis of evaluation.\nThe intuition is that you start from the root and calculate an upper bound if the problem asks the function to be maximized (or lower bound for function minimization in case of TSP where distance is to be minimized) for a function you want to optimize.\n"},{"title":"card_1343","front":"What is a heuristic for solving max independent set?","back":"The simplest reasonable heuristic is to find the lowest-degree vertex, add it to the independent set, and then delete it and all vertices adjacent to it. Repeating this process until the graph is empty gives a maximal independent set, in that it can't be made larger by just adding vertices.\n"},{"title":"card_1344","front":"What is a simple heuristic for vertex cover?","back":"The simplest heuristic for vertex cover selects the vertex with highest degree, adds it to the cover, deletes all adjacent edges, and then repeats until the graph is empty. With the right data structures, this can be done in linear time, and should “usually” produce a “pretty good” cover. However, this cover might be lg n times worse than the optimal cover for certain input graphs.\n"},{"title":"card_1345","front":"What is a heuristic for vertex cover?","back":"A maximal matching can be constructed incrementally, by picking an arbitrary edge e in the graph, deleting any edge sharing a vertex with e, and repeating until the graph is out of edges. Taking both of the vertices for each edge in a maximal matching gives us a vertex cover.\n"},{"title":"card_1346","front":"What is a special case of TSP on an unweighted graph?","back":"If the graph is unweighted, or all the edges have one of two possible cost values, the problem reduces to finding a Hamiltonian cycle.\n"},{"title":"card_1347","front":"What is a heuristic for TSP?","back":"The heuristic starts by finding the minimum spanning tree (MST) of the sites, and then does a depth-first search of the resulting tree. In the course of DFS, we walk over each of the n − 1 edges exactly twice: once going down to discover a new vertex, and once going up when we backtrack. Now define a tour by ordering the vertices by when they were discovered. If the graph obeys the triangle inequality, the resulting tour is at most twice the length of the optimal TSP tour. In practice, it is usually better, typically 15% to 20% over optimal. Furthermore, the running time is bounded by that of computing the MST, which is only O(n lg n) in the case of points in the plane.\n"},{"title":"card_1348","front":"What is HyperLogLog?","back":"HyperLogLog is an algorithm for the count-distinct problem, approximating the number of distinct elements in a multiset.\n\nThe basis of the HyperLogLog algorithm is the observation that the cardinality of a multiset of uniformly distributed random numbers can be estimated by calculating the maximum number of leading zeros in the binary representation of each number in the set. If the maximum number of leading zeros observed is n, an estimate for the number of distinct elements in the set is 2^n.\n\nIn the HyperLogLog algorithm, a hash function is applied to each element in the original multiset, to obtain a multiset of uniformly distributed random numbers with the same cardinality as the original multiset. The cardinality of this randomly distributed set can then be estimated using the algorithm above.\n"},{"title":"card_1349","front":"What is graph partitioning?","back":"Partition the vertices into m roughly equal-sized subsets such that the total edge cost spanning the subsets is at most k.\n"},{"title":"card_1350","front":"Is graph partition NP-complete?","back":"A better partition criterion seeks a small cut that partitions the vertices into roughly equal-sized pieces. Unfortunately, this problem is NP-complete. Fortunately, the heuristics discussed below work well in practice.\n"},{"title":"card_1351","front":"What is the difficulty difference between 3-coloring and 4-coloring a graph?","back":"The famous four-color theorem states that every planar graph can be vertex colored using at most four distinct colors. Efficient algorithms for finding a four-coloring on planar graphs are known, although it is NP-complete to decide whether a given planar graph is three-colorable.\n"},{"title":"card_1352","front":"Is determining the chromatic number of a graph NP-Complete?","back":"Computing the chromatic number of a graph is NP-complete, so if you need an exact solution you must resort to backtracking, which can be surprisingly effective in coloring certain random graphs.\n"},{"title":"card_1353","front":"What is Brook's theorem?","back":"Brook's theorem states that the chromatic number χ(G) ≤ Δ(G) + 1, where Δ(G) is the maximum degree of a vertex of G. Equality holds only for odd-length cycles (which have chromatic number 3) and complete graphs.\n"},{"title":"card_1354","front":"What is the edge-chromatic number?","back":"The minimum number of colors needed to edge color a graph is called its edge-chromatic number by some and its chromatic index by others. Note that an even-length cycle can be edge-colored with 2 colors, while odd-length cycles have an edge-chromatic number of 3.\n"},{"title":"card_1355","front":"What is Vizing's theorem?","back":"Vizing's theorem states that any graph with a maximum vertex degree of Δ can be edge colored using at most Δ + 1 colors.\n"},{"title":"card_1356","front":"What can you say about the difficulty/complexity of graph isomorphism?","back":"No polynomial-time algorithm is known for graph isomorphism, but neither is it known to be NP-complete. Along with integer factorization, it is one of the few important algorithmic problems whose rough computational complexity is still not known. The conventional wisdom is that isomorphism is a problem that lies between P and NP-complete if P <> NP.\n"},{"title":"card_1357","front":"How can adjacency matrices be used to compute paths?","back":"Taking the adjacency matrix of G and raising it to the kth power gives a matrix where Gk[i, j] counts the number of (non-simple) paths from i to j.\n"},{"title":"card_1358","front":"What does it mean to be isomorphism-complete?","back":"A problem is said to be isomorphism-complete if it is provably as hard as isomorphism.\n"},{"title":"card_1359","front":"What is the difficulty of minimum Steiner tree?","back":"The general minimum Steiner tree problem is NP-hard, and remains so under a broad range of restrictions.\n"},{"title":"card_1360","front":"What is a heuristic for finding Steiner trees?","back":"Construct a graph modeling your input, setting the weight of edge (i, j) equal to the distance from point i to point j. Find an MST of this graph. You are guaranteed a provably good approximation for both Euclidean and rectilinear Steiner trees.\n"},{"title":"card_1361","front":"Is Euclidean Steiner tree in NP?","back":"Euclidean Steiner tree is not known to be in NP, because of numerical issues in representing distances.\n"},{"title":"card_1362","front":"How can I find a good feedback edge set?","back":"An effective linear-time heuristic constructs a vertex ordering (topological sort) and then deletes any arc going in the wrong direction. At least half the arcs must go either left-to-right or right-to-left for any vertex order, so take the smaller partition as your feedback set.\n"},{"title":"card_1363","front":"What can be said of the relationship between convex hull and graph diameter?","back":"The diameter of a set of points is the pair of points that lie a maximum distance apart. \nThe diameter must be between two points on the convex hull.\n"},{"title":"card_1364","front":"Triangulation - how can you partition the interior of the point set or polyhedron into triangles?","back":"A triangulation in the plane is constructed by adding nonintersecting chords between the vertices until no more such chords can be added. The simplest such O(n lg n) algorithm first sorts the points by x-coordinate. It then inserts them from left to right as per the convex-hull algorithm, building the triangulation by adding a chord to each point newly cut off from the hull.\n"},{"title":"card_1365","front":"What is a Voronoi diagram?","back":"Voronoi diagrams represent the region of influence around each of a given set of sites. If these sites represent the locations of McDonald's restaurants, the Voronoi diagram partitions space into cells around each restaurant. For each person living in a particular cell, the defining McDonald's represents the closest place to get a Big Mac.\n"},{"title":"card_1366","front":"How can you find the nearest neighbor of query point q from among a fixed set of points?","back":"Finding the nearest neighbor of query point q from among a fixed set of points S is simply a matter of determining the cell in the Voronoi diagram of S that contains q.\nOr use a kd-tree to divide and conquer the points.\n"},{"title":"card_1367","front":"Suppose McDonald's wants to open another restaurant. To minimize interference with existing McDonald's, it should be located as far away from the closest restaurant as possible. How can you find it?","back":"This location is always at a vertex of the Voronoi diagram, and can be found in a linear-time search through all the Voronoi vertices.\n"},{"title":"card_1368","front":"What is a Voronoi vertex?","back":"A Voronoi vertex defines the center of the largest empty circle among the points.\n"},{"title":"card_1369","front":"What is a Delaunay triangulation?","back":"The Delaunay triangulation maximizes the minimum angle over all triangulations (avoids skinny triangles). Furthermore, it is easily constructed as the dual of the Voronoi diagram.\n"},{"title":"card_1370","front":"What code can you use for 2D Voronoi diagrams and Delaunay triangulations?","back":"Fortune's Sweep2 is a widely used 2D code for Voronoi diagrams and Delaunay triangulations, written in C. This code is simple to work with if all you need is the Voronoi diagram.\n"},{"title":"card_1371","front":"What is a popular library for convex hull as well as other 2D geometric algorithms?","back":"Qhull is a popular low-dimensional convex-hull code, useful for from two to about eight dimensions. It is written in C and can also construct Delaunay triangulations, Voronoi vertices, furthest-site Voronoi vertices, and half-space intersections.\n"},{"title":"card_1372","front":"What is the problem in using a high-dimension kd-tree for finding nearest neighbors?","back":"Searches in high-dimensional spaces become hard because a sphere of radius r, representing all the points with distance ≤ r from the center, progressively fills up less volume relative to a cube as the dimensionality increases. Thus, any data structure based on partitioning points into enclosing volumes will become progressively less effective.\n"},{"title":"card_1373","front":"What is a library for approximate nearest neighbor searching in arbitrarily high dimensions?","back":"ANN is a C++ library for both exact and approximate nearest neighbor searching in arbitrarily high dimensions. It performs well for searches over hundreds of thousands of points in up to about 20 dimensions. It supports all lp distance norms, including Euclidean and Manhattan distance.\n"},{"title":"card_1374","front":"What is a tool for visualizing and experimenting with nearest-neighbor and orthogonal-range queries in high-dimensional data sets?","back":"Ranger is a tool for visualizing and experimenting with nearest-neighbor and orthogonal-range queries in high-dimensional data sets, using multidimensional search trees. Four different search data structures are supported by Ranger: naive kd-trees, median kd-trees, nonorthogonal kd-trees, and the vantage point tree.\n"},{"title":"card_1375","front":"What turns out to be the only viable solution for high-dimensional range search?","back":"kd-trees are likely to work just fine in the plane. In higher dimensions, they provide the only viable solution to the problem.\n"},{"title":"card_1376","front":"Is bin-packing NP-Complete?","back":"Even the most elementary-sounding bin-packing problems are NP-complete.\n"},{"title":"card_1377","front":"What is the best heuristic for bin packing?","back":"Analytical and empirical results suggest that first-fit decreasing is the best heuristic. Sort the objects in decreasing order of size, so that the biggest object is first and the smallest last. Insert each object one by one into the first bin that has room for it. If no bin has room, we must start another bin. In the case of one-dimensional bin packing, this can never require more than 22% more bins than necessary and usually does much better. First-fit decreasing has an intuitive appeal to it, for we pack the bulky objects first and hope that little objects can fill up the cracks.\nFirst-fit decreasing is easily implemented in O(n lg n + bn) time, where b ≤ min(n, m) is the number of bins actually used. Simply do a linear sweep through the bins on each insertion. A faster O(n lg n) implementation is possible by using a binary tree to keep track of the space remaining in each bin.\n"},{"title":"card_1378","front":"What is medial-axis transformation?","back":"The medial-axis transformation is useful in thinning a polygon, or as is sometimes said, finding its skeleton. The goal is to extract a simple, robust representation of the shape of the polygon.\n\nThe medial-axis transform of a polygon P is simply the portion of the line-segment Voronoi diagram that lies within P. Any line-segment Voronoi diagram code thus suffices to do polygon thinning.\n"},{"title":"card_1379","front":"What is triangulation?","back":"Triangulation is the mother of all polygon partitioning problems, where we partition the interior of the polygon completely into triangles. Triangles are convex and have only three sides, making them the most elementary possible polygon.\n"},{"title":"card_1380","front":"How many triangles can be made from triangulations of an n-vertex polygon?","back":"All triangulations of an n-vertex polygon contain exactly n − 2 triangles.\n"},{"title":"card_1381","front":"What is the Hertel-Mehlhorn heuristic for convex decomposition?","back":"The Hertel-Mehlhorn heuristic for convex decomposition using diagonals is simple and efficient. It starts with an arbitrary triangulation of the polygon and then deletes any chord that leaves only convex pieces. A chord deletion creates a non-convex piece only if it creates an internal angle that is greater than 180 degrees.\n"},{"title":"card_1382","front":"What is a heuristic for shape similarity of graphs?","back":"A more powerful approach to shape similarity uses thinning to extract a tree-like skeleton for each object. This skeleton captures many aspects of the original shape. The problem now reduces to comparing the shape of two such skeletons, using such features as the topology of the tree and the lengths/slopes of the edges. This comparison can be modeled as a form of subgraph isomorphism, with edges allowed to match whenever their lengths and slopes are sufficiently similar.\n"},{"title":"card_1383","front":"What is a Minkowski sum and what is it used for?","back":"Minkowski sums are useful geometric operations that can fatten objects in appropriate ways. For example, a popular approach to motion planning for polygonal robots in a room with polygonal obstacles fattens each of the obstacles by taking the Minkowski sum of them with the shape of the robot. This reduces the problem to the (more easily solved) case of point robots.\n"},{"title":"card_1384","front":"What is the difficulty of vertex cover and what is the limit of current approximation algorithms?","back":"Set cover must be at least as hard as vertex cover, so it is also NP-complete. In fact, it is somewhat harder. Approximation algorithms do no worse than twice optimal for vertex cover, but the best approximation algorithm for set cover is Θ(lg n) times optimal.\n"},{"title":"card_1385","front":"What is an effective heuristic of set cover?","back":"Greedy is the most natural and effective heuristic for set cover. Begin by selecting the largest subset for the cover, and then delete all its elements from the universal set. We add the subset containing the largest number of remaining un-covered elements repeatedly until all are covered.\n"},{"title":"card_1386","front":"What is a heuristic of set packing?","back":"The right heuristics for set packing are greedy, and similar to those of set cover. If we seek a packing with many (few) sets, then we repeatedly select the smallest (largest) subset, delete all subsets from S that clash with it, and repeat. As usual, augmenting this approach with some exhaustive search or randomization (in the form of simulated annealing) is likely to yield better packings at the cost of additional computation.\n"},{"title":"card_1387","front":"What does the Boyer-Moore algorithm do that saves time?","back":"The Boyer-Moore algorithm matches the pattern against the text from right to left, and can avoid looking at large chunks of text on a mismatch. Suppose the pattern is abracadabra, and the eleventh character of the text is x. This pattern cannot match in any of the first eleven starting positions of the text, and so the next necessary position to test is the 22nd character. If we get very lucky, only n/m characters need ever be tested. The Boyer-Moore algorithm involves two sets of jump tables in the case of a mismatch: one based on pattern matched so far, the other on the text character seen in the mismatch.\n"},{"title":"card_1388","front":"What is the performance and caveats of Boyer-Moore?","back":"It is worth it in practice for patterns of length m > 5, unless the pattern is expected to occur many times in the text. Its worst-case performance is O(n + rm), where r is the number of occurrences of p in t.\n"},{"title":"card_1389","front":"What is an efficient use of suffix trees/arrays?","back":"Suppose you are building a program to repeatedly search a particular text database, such as the Bible. Since the text remains fixed, it pays to build a data structure to speed up search queries. The suffix tree and suffix array data structures are the right tools for the job.\n"},{"title":"card_1390","front":"What is a better method for searching many texts using the same patterns?","back":"Suppose you are building a program to screen out dirty words from a text stream. Here, the set of patterns remains stable, while the search texts are free to change. In such applications, we may need to find all occurrences of any of k different patterns where k can be quite large.\n\nPerforming a linear-time scan for each pattern yields an O(k(m + n)) algorithm. If k is large, a better solution builds a single finite automaton that recognizes all of these patterns and returns to the appropriate start state on any character mismatch. The Aho-Corasick algorithm builds such an automaton in linear time. Space savings can be achieved by optimizing the pattern recognition automaton. This approach was used in the original version of fgrep.\n"},{"title":"card_1391","front":"What can you say about the performance of Rabin-Karp?","back":"The Rabin-Karp algorithm uses a hash function to perform string matching in linear expected time. Its worst-case time remains quadratic, and its performance in practice appears somewhat worse than other character comparison methods.\n"},{"title":"card_1392","front":"What can you use to take advantage of large word sizes (in registers) to do string matching?","back":"A recent approach to string-matching exploits the fact that modern computers can do operations on (say) 64-bit words in a single gulp. This is long enough to hold eight 8-bit ASCII characters, providing motivation to design bit-parallel algorithms, which do more than one comparison with each operation.\n\nThe basic idea is quite clever. Construct a bit-mask Bα for each letter α of the alphabet, such that ith-bit Bα[i] = 1 iff the ith character of the pattern is α. Now suppose you have a match bit-vector Mj for position j in the text string, such that Mj[i] = 1 iff the first i bits of the pattern exactly match the (j − i + 1)st through jth character of the text. We can find all the bits of Mj+1 using just two operations by (1) shifting Mj one bit to the right, and then (2) doing a bitwise AND with Bα, where α is the character in position.\n"},{"title":"card_1393","front":"How does the Burrows-Wheeler transform work and what is its performance?","back":"A particularly interesting simplification results from applying the Burrows-Wheeler transform to the input string. This transform sorts all n cyclic shifts of the n character input, and then reports the last character of each shift. As an example, the cyclic shifts of ABAB are ABAB, BABA, ABAB, and BABA. After sorting, these become ABAB, ABAB, BABA, and BABA. Reading the last character of each of these strings yields the transform result: BBAA.\n\nProvided the last character of the input string is unique (e.g., end-of-string), this transform is perfectly reversible to the original input! The Burrows-Wheeler string is typically 10-15% more compressible than the original text, because repeated words turn into blocks of repeated characters. Further, this transform can be computed in linear time.\n"},{"title":"card_1394","front":"What are Huffman codes?","back":"Huffman codes replace each alphabet symbol by a variable-length code string. Using eight bits-per-symbol to encode English text is wasteful, since certain characters (such as “e”) occur far more frequently than others (such as “q”). Huffman codes assign “e” a short code word, and “q” a longer one to compress text.\n"},{"title":"card_1395","front":"How do Lempel-Ziv algorithms work?","back":"Lempel-Ziv algorithms (including the popular LZW variant) compress text by building a coding table on the fly as we read the document. The coding table changes at every position in the text. A clever protocol ensures that the encoder and decoder are both always working with the exact same code table, so no information is lost.\n"},{"title":"card_1396","front":"What can you say about the tradeoffs in compression algorithms?","back":"There is a natural tradeoff between compression ratio and compression time. Another choice is bzip2, which uses the Burrows-Wheeler transform. It produces tighter encodings than gzip at somewhat greater cost in running time. Going to the extreme, other compression algorithms devote enormous run times to squeeze every bit out of a file.\n"},{"title":"card_1397","front":"How can finite automata be represented in a directed graph?","back":"Finite state machines are defined by directed graphs. Each vertex represents a state, and each character-labeled edge defines a transition from one state to another on receipt of the given alphabet symbol. Such automata can be represented using any graph data structure.\n"},{"title":"card_1398","front":"What is a caveat and hardness of converting non-deterministic to deterministic finite automata?","back":"Converting an NFA to a DFA might cause an exponential blowup in the number of states, which perversely might then be eliminated when minimizing the DFA. This exponential blowup makes most NFA minimization problems PSPACE-hard, which is even worse than NP-complete.\n"},{"title":"card_1399","front":"How can you compute the longest common substring of a set of strings in linear time?","back":"The longest common substring of a set of strings can be identified in linear time using suffix trees. The trick is to build a suffix tree containing all the strings, label each leaf with the input string it represents, and then do a depth-first traversal to identify the deepest node with descendants from each input string.\n"},{"title":"card_1400","front":"How can you convert edit distance into common scattered subsequence?","back":"This algorithm is a special case of the dynamic program edit-distance computation.\n\nLet M[i, j] denote the number of characters in the longest common substring of S[1], . . . , S[i] and T [1], . . . , T [j]. When S[i] <> T[j], there is no way the last pair of characters could match, so M[i, j] = max(M[i, j − 1], M[i − 1, j]). But if S[i] = T[j], we have the option to select this character for our substring, so M[i, j] = max(M[i − 1, j − 1] + 1, M[i − 1, j], M[i, j − 1]).\n\nThis recurrence computes the length of the longest common subsequence in O(nm) time. We can reconstruct the actual common substring by walking backward from M[n, m] and establishing which characters were matched along the way.\n"},{"title":"card_1401","front":"What is the difficulty of shortest common superstring?","back":"Shortest common superstring is NP-complete for all reasonable classes of strings.\n"},{"title":"card_1402","front":"What is the standard approach to approximating shortest common superstring?","back":"The greedy heuristic provides the standard approach to approximating shortest common superstring. Identify which pair of strings have the maximum overlap. Replace them by the merged string, and repeat until only one string remains. This heuristic can actually be implemented in linear time. The seemingly most time-consuming part is in building the overlap graph. The brute-force approach to finding the maximum overlap of two length-L strings takes O(L2) for each of O(n^2) string pairs. However, faster times are possible by using suffix trees. Build a tree containing all suffixes of all strings of S. String Si overlaps with Sj iff a suffix of Si matches the prefix of Sj — an event defined by a vertex of the suffix tree. Traversing these vertices in order of distance from the root defines the appropriate merging order.\n"},{"title":"card_1403","front":"What is the smallest addressable data item on many CPUs?","back":"A byte is eight bits and it is the smallest addressable data item on many CPUs. That is, the CPU can efficiently retrieve data on an 8-bit boundary from memory.\n"},{"title":"card_1404","front":"What is the range representable by n bits?","back":"range −2^(n−1) to +2^(n−1)−1\n"},{"title":"card_1405","front":"What happens when you negate the smallest negative value in the two's complement numbering system?","back":"It becomes itself.\nIn general, you cannot negate the smallest negative value in the two's complement numbering system.\n"},{"title":"card_1406","front":"What does it mean if the LO n bits of a binary number all contain zero?","back":"If the LO n bits of a binary number all contain zero, then the number is evenly divisible by 2n.\n"},{"title":"card_1407","front":"Why should you be careful about mixing variables of different sizes within the same arithmetic expression or assignment statement?","back":"The important thing to realize about sign and zero extension is that they aren't always free. Assigning a smaller integer to a larger integer may require more machine instructions (taking longer to execute) than moving data between two like-sized integer variables.\n"},{"title":"card_1408","front":"What conditions do you have to have in order to sign contract a numeric value?","back":"First, the HO bytes must all contain either zero or 0xFF. If you encounter any other values, you cannot sign contract the value. Second, the HO bit of your resulting value must match every bit you've removed from the number.\n"},{"title":"card_1409","front":"What is saturation?","back":"Saturation is another way to reduce the size of an integer value. Saturation is useful when you want to convert a larger object to a smaller object and you're willing to live with possible loss of precision.\n"},{"title":"card_1410","front":"On the Intel 80x86 processor family, what do the MMX instruction extensions provide?","back":"The MMX instruction extensions provide saturation capabilities. Most CPUs' standard instruction sets, as well as most high-level languages, do not provide direct support for saturation, but saturation is not difficult.\n"},{"title":"card_1411","front":"What is BCD?","back":"The binary-coded decimal (BCD) format, as its name suggests, encodes decimal values (0-9) using a binary representation.\n"},{"title":"card_1412","front":"What are BCD values?","back":"BCD values consist of a sequence of nibbles, with each nibble representing a value in the range 0..9.\n"},{"title":"card_1413","front":"What is possible with 16-bit integer, 16-bit fractional format?","back":"Certain 3D gaming applications may produce faster computations using a 16:16 (16-bit integer, 16-bit fractional) format rather than a 32-bit floating-point format.\n"},{"title":"card_1414","front":"What is an advantage of binary decimal format over 2 digit decimal format?","back":"Given the accuracy most financial computations require (generally four digits to the right of the decimal point is the minimum precision serious financial transactions require), it's usually better to use a binary format.\n"},{"title":"card_1415","front":"What is an advantage of scaled numeric format?","back":"One advantage of the scaled numeric format is that you can choose any base, not just decimal, for your format.\n"},{"title":"card_1416","front":"What is rational representation?","back":"Rational representation uses pairs of integers to represent fractional values. One integer represents the numerator (n) of a fraction, and the other represents the denominator (d). The actual value is equal to n/d.\n"},{"title":"card_1417","front":"How can you test if a bit is set?","back":"If you logically AND a value with a bit string that contains a one in a certain bit position, the result of the logical AND will be zero if the corresponding bit contains a zero, and the result will be nonzero if the bit is set.\n"},{"title":"card_1418","front":"How can you test if a number is divisible by 16?","back":"(ValueToTest & 0xF) == 0\n"},{"title":"card_1419","front":"How can you write a module-n counter for mod 32 using AND to avoid division?","back":"(cntr + 1) & 0x3F; // AND with 6-bit mask, truncating a value to 0-31\n"},{"title":"card_1420","front":"What is floating-point precision?","back":"The number of digits or bits maintained in a computation.\n"},{"title":"card_1421","front":"What is one way to minimize floating point error accumulation?","back":"If you are performing a chain calculation involving addition and subtraction, you should attempt to group the operations so that you can add or subtract values whose magnitudes are close to one another before adding or subtracting values whose magnitudes are not as close.\n"},{"title":"card_1422","front":"What is a caveat for floating-point addition and subtraction?","back":"Whenever subtracting two numbers with the same signs or adding two numbers with different signs, the accuracy of the result may be less than the precision available in the floating-point format.\n"},{"title":"card_1423","front":"What can you do to avoid floating-point error accumulation issues involving addition, subtraction, multiplication, and division?","back":"When performing a chain of calculations involving addition, subtraction, multiplication, and division, try to perform the multiplication and division operations first.\n"},{"title":"card_1424","front":"What can you do to avoid floating point error issues when you multiply and divide numbers?","back":"When multiplying and dividing sets of numbers, try to multiply and divide numbers that have the same relative magnitudes.\n"},{"title":"card_1425","front":"How can you avoid issues in precise comparison on floating point numbers?","back":"if( abs(Value1 − Value2) <= error ) then ...\n"},{"title":"card_1426","front":"What can you do to compare 2 floating-point numbers?","back":"If you determine that the values are not equal to one another within the desired error tolerance, then you can compare them to see if one value is less than or greater than the other. This is known as a miserly approach to comparing for less than or greater than (that is, we try to find as few values that are less than or greater than as possible).\n"},{"title":"card_1427","front":"What is the eager approach to floating-point comparison?","back":"An eager approach attempts to make the result of the comparison true as often as possible. Given two values that you want to compare, and an error tolerance you’re interested in achieving, here’s how you’d eagerly compare the two values for less than or greater than:\n\nif( A < (B + error)) then Eager_A_lessthan_B; \nif( A > (B − error)) then Eager_A_greaterthan_B;\n"},{"title":"card_1428","front":"What is special about extended precision?","back":"Extended precision contains 16 extra bits that the calculations can use as guard bits before rounding down to a double-precision value when storing the result.\n"},{"title":"card_1429","front":"What is the format of single-precision?","back":"The single-precision format uses a 24-bit mantissa and an 8-bit exponent. The mantissa usually represents a value between 1.0 and just less than 2.0. The mantissa usually represents a value between 1.0 and just less than 2.0. The HO bit of the mantissa is always assumed to be one and represents a value just to the left of the binary point. The remaining 23 mantissa bits appear to the right of the binary point and represent the value:\n1.mmmmmmm mmmmmmmm mmmmmmmm\n"},{"title":"card_1430","front":"What is the double-precision format?","back":"The double-precision format helps overcome the problems of the single-precision floating-point. Using twice the space, the double-precision format has an 11-bit excess-1,023 exponent and a 53-bit mantissa (including an implied HO bit of one) plus a sign bit. This provides a dynamic range of about 10±308 and 14 1/2 digits of precision, which is sufficient for most applications.\n"},{"title":"card_1431","front":"What is the extended-precision format?","back":"The extended-precision format provides a 64-bit mantissa, a 15-bit excess-16,383 exponent, and a 1-bit sign.\n"},{"title":"card_1432","front":"How does Intel treat extended-precision?","back":"Intel always works in extended-precision format. It converts to extended precision before doing computations. By doing so, Intel guarantees a large number of guard bits are present to ensure the accuracy of your computations. By performing all computations using 80 bits, Intel helps ensure (but not guarantee) that you will get full 32- or 64-bit accuracy in your computations.\n"},{"title":"card_1433","front":"How do you normalize a floating-point value?","back":"Almost any unnormalized value can be normalized by shifting the mantissa bits to the left and decrementing the exponent until a one appears in the HO bit of the mantissa.\n"},{"title":"card_1434","front":"How does rounding-up affect a floating-point value?","back":"Rounding up leaves the value alone if the guard bits are all zero, but if the current mantissa does not exactly fit into the destination bits, then rounding up sets the result to the smallest possible larger value in the floating-point format.\n"},{"title":"card_1435","front":"How does rounding down affect a floating-point value and how is it different from truncation?","back":"Rounding down is just like rounding up, except it rounds the result to the largest possible smaller value. This may sound like truncation, but there is a subtle difference between truncation and rounding down. Truncation always rounds towards zero. For positive numbers, truncation and rounding down do the same thing. However, for negative numbers, truncation simply uses the existing bits in the mantissa, whereas rounding down will actually add a one bit to the LO position if the result was negative.\n"},{"title":"card_1436","front":"How can you represent NaN in floating point?","back":"If the exponent contains all ones and the mantissa is nonzero (discounting the implied bit), then the HO bit of the mantissa (again discounting the implied bit) determines whether the value represents a quiet not-a-number (QNaN) or a signaling not-a-number (SNaN) (see Table 4-1). These not-a-number (NaN) results tell the system that some serious miscalculation has taken place and that the result of the calculation is completely undefined.\n"},{"title":"card_1437","front":"How can you represent infinity in floating-point?","back":"Two other special values are represented when the exponent contains all one bits, and the mantissa contains all zeros. In such a case, the sign bit determines whether the result is the representation for +infinity or −infinity.\n"},{"title":"card_1438","front":"How can you convert an ASCII character between uppercase and lowercase?","back":"You can use this fact to quickly convert an alphabetic character between upper- and lowercase by simply inverting bit five. If you have an uppercase character, you can force it to lowercase by setting bit five to one. If you have a lowercase character and you wish to force it to uppercase, you can do so by setting bit five to zero.\n"},{"title":"card_1439","front":"How can you obtain the binary representation of an ASCII numeric value?","back":"By stripping away (setting to zero) the HO nibble of the ASCII code, you obtain the binary representation of that digit. Conversely, you can convert a binary value in the range 0..9 to its ASCII character representation by simply setting the HO nibble to %0011, or the decimal value 3.\n"},{"title":"card_1440","front":"What are length-prefixed strings?","back":"Length-prefixed strings overcome some of the problems with zero-terminated strings. Length-prefixed strings are common in languages like Pascal; they generally consist of a single byte that specifies the length of the string, followed by zero or more 8-bit character codes. In a length-prefixed scheme, the string “abc” would consist of four bytes: the length byte (0x03), followed by a, b, and c.\n"},{"title":"card_1441","front":"What are static strings?","back":"Arrays of characters that you will use to hold zero-terminated strings in C/C++. While the program is running, there is no way to increase the maximum sizes of these static strings. Nor is there any way to reduce the storage they will use.\n"},{"title":"card_1442","front":"What are pseudo-dynamic strings?","back":"Pseudo-dynamic strings are those whose length the system sets at run time by calling a memory-management function like malloc to allocate storage for the string. However, once the system allocates storage for the string, the maximum length of the string is fixed.\n"},{"title":"card_1443","front":"What are dynamic strings?","back":"Dynamic string systems, which typically use a descriptor-based format, will automatically allocate sufficient storage for a string object whenever you create a new string or otherwise do something that affects an existing string. This is called copy-on-write?\n"},{"title":"card_1444","front":"Is constrained or unconstrained optimization NP-Complete?","back":"No.\n"},{"title":"card_1445","front":"Is linear programming NP-Complete?","back":"No.\n"},{"title":"card_1446","front":"Is mixed (integer and linear programming) NP-Complete?","back":"Yes, to solve to optimality. But there are techniques that work well in practice.\n"},{"title":"card_1447","front":"Is factoring numbers in NP?","back":"The prime factorization problem is in the NP class, but we don't know if it is NP-hard. In other words, there is currently no proof that prime factorization problem cannot be solved polynomial time (in P). Subsequently there is no proof that algorithms that rely on prime factorization being hard are rendered ineffective.\n"},{"title":"card_1448","front":"Is calculating Eulerian path NP-Complete?","back":"No.\n"},{"title":"card_1449","front":"Is calculating Eulerian cycle NP-Complete?","back":"No.\n"},{"title":"card_1450","front":"For non-planar graphs, it is useful to minimize the number of crossing edges to represent the graph in a flat manner. What is a problem with this approach?","back":"Computing the crossing number of a graph is NP-Complete.\n"},{"title":"card_1451","front":"Is detection of intersection (collision) of two graphs NP-Complete?","back":"No, but it can be very complicated.\n"},{"title":"card_1452","front":"What is the difference between set cover and set packing?","back":"Set cover allows overlap, while set packing doesn't.\n"},{"title":"card_1453","front":"Is set cover NP-Complete?","back":"The decision version of set covering is NP-complete, and the optimization/search version of set cover is NP-hard.\n"},{"title":"card_1454","front":"Is set partition NP-Complete?","back":"No. Don't confuse it with set packing.\n"},{"title":"card_1455","front":"Is set packing NP-Complete?","back":"Yes. It's not only NP-complete, but its optimization version (general maximum set packing problem) has been proven as difficult to approximate as the maximum clique problem; in particular, it cannot be approximated within any constant factor.\n"},{"title":"card_1456","front":"What is copy on write with strings?","back":"Whenever a string function needs to change some characters in a dynamic string, the function first makes a copy of the string and then makes whatever modifications are necessary to the copy of the data.\n"},{"title":"card_1457","front":"What are the three components of a von Neumann system?","back":"A typical von Neumann system has three major components: the central processing unit (CPU), memory, and input/output (I/O)\n"},{"title":"card_1458","front":"How does a CPU see I/O devices?","back":"To the CPU, most I/O devices look like memory.\n"},{"title":"card_1459","front":"What is the data bus?","back":"CPUs use the data bus to shuffle data between the various components in a computer system. The size of this bus varies widely among CPUs. Indeed, bus size is one of the main attributes that defines the “size” of the processor.\n"},{"title":"card_1460","front":"What is the size of a modern data bus?","back":"For the most part, the CPUs in personal computers tend to use 32-bit or 64-bit data buses (and 64-bit data buses are the most prevalent).\n"},{"title":"card_1461","front":"What is the address bus and how does it work?","back":"When the software wants to access a particular memory location or I/O device, it places the corresponding address on the address bus. Circuitry within the device checks this address and transfers data if there is an address match.\n"},{"title":"card_1462","front":"How much memory can be addresses with n address lines?","back":"With n address lines, the processor can access 2^n unique addresses (because there are 2^n unique values in an n-bit binary number). Therefore, the number of bits on the address bus will determine the maximum number of addressable memory and I/O locations. A 64-bit address range is truly infinite as far as memory is concerned. No one will ever put 2^64 bytes of memory into a computer system and feel that they need more. It's more than atoms in the universe.\n"},{"title":"card_1463","front":"What is the control bus?","back":"The control bus is an eclectic collection of signals that control how the processor communicates with the rest of the system. The system uses two lines on the control bus, read and write, to determine the data flow direction (CPU to memory, or memory to CPU). So when the CPU wants to write data to memory, it asserts (places a signal on) the write control line. When the CPU wants to read data from memory, it asserts the read control line.\n"},{"title":"card_1464","front":"What are the byte enable lines?","back":"The byte enable lines appear on the control bus of some CPUs that support byte-addressable memory. These control lines allow 16-, 32-, and 64-bit processors to deal with smaller chunks of data by communicating the size of the accompanying data.\n"},{"title":"card_1465","front":"What are the 2 address spaces supported by the one address bus?","back":"The 80x86 family, unlike many other processors, provides two distinct address spaces: one for memory and one for I/O.However, it does not have two separate physical address buses (for I/O and memory). Instead, the system shares the address bus for both I/O and memory addresses. Additional control lines decide whether the address is intended for memory or I/O.\n"},{"title":"card_1466","front":"What does the CPU to save data like this: Memory[125] = 0","back":"To execute the equivalent of the statement Memory[125] = 0; the CPU places the value zero on the data bus, the address 125 on the address bus, and asserts the write line on the control bus.\n"},{"title":"card_1467","front":"How does the 80x86 family store a data word?","back":"The 80x86 family stores the LO byte of a word at the address specified and the HO byte at the next location. Therefore, a word consumes two consecutive memory addresses (as you would expect, because a word consists of two bytes). Similarly, a double word consumes four consecutive memory locations.\n"},{"title":"card_1468","front":"What is a byte-addressable memory array?","back":"The term byte-addressable memory array means that the CPU can address memory in chunks as small as a single byte. It also means that this is the smallest unit of memory you can access at once with the processor.\n"},{"title":"card_1469","front":"What bits are used on a 64-bit data bus?","back":"Only the LO 48 bits are used on 64-bit data buses. That's 256 terabytes. Good enough for now.\n"},{"title":"card_1470","front":"What is the address alignment on a 32-bit memory interface?","back":"With a 32-bit memory interface, the address placed on the address bus is always some multiple of four.\n"},{"title":"card_1471","front":"How can a 32-bit CPU can access a double word in a single memory operation?","back":"A 32-bit CPU can access a double word in a single memory operation only if the address of that value is evenly divisible by four.\n"},{"title":"card_1472","front":"How do modern Intel processors deal with non-aligned data?","back":"The Pentium and later processors provide a 64-bit data bus and special cache memory that reduces the impact of non-aligned data access. Although there may still be a penalty for accessing data at an inappropriate address, modern x86 CPUs suffer from the problem less frequently than the earlier CPUs.\n"},{"title":"card_1473","front":"What is the endianness of TCP/IP and some other network protocols?","back":"When transmitting data across networks, the canonical form is usually big endian because TCP/IP and some other network protocols use the big endian format.\n"},{"title":"card_1474","front":"When transmitting data across the Universal Serial Bus, what is the endianness?","back":"The canonical format is little endian.\n"},{"title":"card_1475","front":"What are the 4 steps to ensure n log n performance on quick sort?","back":"- randomize input first\n- use median of three to determine pivot\n- at fewer than 20 elements, end recursion early and do insertion sort\n- do the smaller partition first\n"},{"title":"card_1476","front":"How can you convert from one endianness to another?","back":"To convert between the endian forms, you must do a mirror-image swap of the bytes in the object. To cause a mirror-image swap, you must swap the bytes at opposite ends of the binary number, and then work your way towards the middle of the object swapping pairs of bytes as you go along.\n"},{"title":"card_1477","front":"What is the system clock?","back":"The system clock is an electrical signal on the control bus that alternates between zero and one at a periodic rate. All activity within the CPU is synchronized with the edges (rising or falling) of this clock signal.\n"},{"title":"card_1478","front":"What is the system clock frequency and system clock period?","back":"The frequency with which the system clock alternates between zero and one is the system clock frequency and the time it takes for the system clock to switch from zero to one and back to zero is the clock period. One full period is also called a clock cycle.\n"},{"title":"card_1479","front":"What is the clock period for a 1 GHz processor?","back":"A CPU running at 1 GHz would have a clock period of one nanosecond (ns), or one billionth of a second.\n"},{"title":"card_1480","front":"How does the clock limit a CPU?","back":"Because all CPU operations are synchronized with the clock, the CPU cannot perform tasks any faster than the clock runs. However, just because a CPU is running at some clock frequency doesn't mean that it executes that many operations each second.\n"},{"title":"card_1481","front":"What is the memory access time?","back":"The memory access time is the number of clock cycles between a memory request (read or write) and when the memory operation completes. This is an important value, because longer memory access times result in lower performance.\n"},{"title":"card_1482","front":"Why does the CPU use wait states for memory accesses?","back":"The CPU doesn't wait for memory. The access time is specified by the bus clock frequency. If the memory subsystem doesn't work fast enough to keep up with the CPU's expected access time, the CPU will read garbage data on a memory read operation and will not properly store the data on a memory write. This will surely cause the system to fail.\n"},{"title":"card_1483","front":"How do memory access waits work?","back":"Almost every general-purpose CPU in existence provides a pin (whose signal appears on the control bus) that allows the insertion of wait states. If necessary, the memory address decoding circuitry asserts this signal to give the memory sufficient access time.\n"},{"title":"card_1484","front":"How does the CPU avoid excessive wait states?","back":"However, we're not doomed to slow execution because of added wait states. There are several tricks hardware designers can employ to achieve zero wait states most of the time. The most common of these is the use of cache memory.\n"},{"title":"card_1485","front":"What are temporal locality of reference and spatial locality of reference?","back":"If you look at a typical program, you'll discover that it tends to access the same memory locations repeatedly. Furthermore, you'll also discover that a program often accesses adjacent memory locations. The technical names given to these phenomena are temporal locality of reference and spatial locality of reference. When exhibiting spatial locality, a program accesses neighboring memory locations within a short period after the initial memory access.\n"},{"title":"card_1486","front":"What is temporal locality of reference?","back":"When displaying temporal locality of reference, a program accesses the same memory location repeatedly during a short time.\n"},{"title":"card_1487","front":"How can a CPU keep data in cache?","back":"Cache memory can dynamically reassign addresses. This allows the system to keep recently accessed values in the cache. Addresses that the CPU has never accessed or hasn't accessed in some time remain in main (slow) memory. Because most memory accesses are to recently accessed variables (or to locations near a recently accessed location), the data generally appears in cache memory.\n"},{"title":"card_1488","front":"How can CPUs optimize when a cache miss occurs?","back":"When a cache miss occurs most caching systems will read several consecutive bytes of main memory (engineers call this block of data a cache line). 80x86 CPUs, for example, read between 16 and 64 bytes upon a cache miss.\n"},{"title":"card_1489","front":"What is the benefit of a large, third-level cache?","back":"For programs that manipulate considerable data, yet exhibit locality of reference, a third-level caching subsystem can be very effective.\n"},{"title":"card_1490","front":"What is direct addressing mode?","back":"The direct addressing mode encodes a variable's memory address as part of the actual machine instruction that accesses the variable.\n"},{"title":"card_1491","front":"What is indirect addressing mode?","back":"The indirect addressing mode typically uses a register to hold a memory address (there are a few CPUs that use memory locations to hold the indirect address, but this form of indirect addressing is rare in modern CPUs).\n"},{"title":"card_1492","front":"What is indexed addressing mode?","back":"The indexed addressing mode combines the direct and indirect addressing modes into a single addressing mode. Specifically, the machine instructions using this addressing mode encode both an offset (direct address) and a register in the bits that make up the instruction. At run time, the CPU computes the sum of these two address components to create an effective address.\n"},{"title":"card_1493","front":"What is a pointer?","back":"A pointer is a memory variable whose value is the address of some other memory object.\n"},{"title":"card_1494","front":"How does a CPU lay out an array?","back":"Many optimizing compilers will attempt to place an array starting at a memory address that is an even multiple of some common size like two, four, or eight bytes. This effectively adds padding bytes before the beginning of the array or, if you prefer to think of it this way, it adds padding bytes to the end of the previous object in memory.\n"},{"title":"card_1495","front":"How does a compiler/CPU access A[i][j][k][m]?","back":"Address = Base + (((i * bounds1 + j) * bounds2 + k) * bounds3 + m) * Element_Size\n"},{"title":"card_1496","front":"What are the sizes for Intel 80x86 CPU instructions?","back":"With machine instructions ranging from 1 to almost 15 bytes long.\n"},{"title":"card_1497","front":"What is the flags register?","back":"The flags register, also known as the condition-codes register or program-status word, is an array of Boolean variables in the CPU that tracks whether the previous instruction produced an overflow, a zero result, a negative result, or other such condition.\n"},{"title":"card_1498","front":"What is the BIU and what does it do?","back":"Whenever the execution unit is not using the BIU (Bus Interface Unit), the BIU can fetch additional bytes from the memory that holds the machine instructions and store them in the prefetch queue.\n"},{"title":"card_1499","front":"What can the CPU optimize when the prefetch queue is not full?","back":"If the prefetch queue is not full (generally it can hold between 8 and 32 bytes, depending on the processor) and the BIU is idle on the current clock cycle, fetch the next double word located at the address found in the EIP register at the beginning of the clock cycle.\n"},{"title":"card_1500","front":"What can a CPU do when the instruction decoder is idle?","back":"If the instruction decoder is idle and the current instruction does not require an instruction operand, the CPU should begin decoding the opcode at the front of the prefetch queue. If the current instruction requires an instruction operand, then the CPU begins decoding the byte just beyond that operand in the prefetch queue.\n"},{"title":"card_1501","front":"What hurts performance when instructions are being pipelined?","back":"If you want to write fast code, avoid jumping around in your program as much as possible.\n"},{"title":"card_1502","front":"How is it best to organize branches/jumps in your code?","back":"Therefore, if you can determine, while writing the program, which jump condition occurs most frequently, you should arrange your program so that the most common condition causes the program to continue with the next instruction rather than jump to a separate location.\n"},{"title":"card_1503","front":"How do memory access and instruction prefetches contend for resources?","back":"Don't forget, the CPU needs to use the bus for other purposes. Instructions that access memory compete with the prefetch queue for access to the bus.\n"},{"title":"card_1504","front":"How can bus contention occur?","back":"Bus contention can occur whenever an instruction needs to access an item in memory. Contention for the address and data bus may develop because the CPU will be trying to fetch data from memory and write data to memory simultaneously.\n"},{"title":"card_1505","front":"What is a pipeline stall and what does it help to solve?","back":"One simplistic way to handle bus contention is through a pipeline stall. The CPU, when faced with contention for the bus, gives priority to the instruction farthest along in the pipeline. This causes the later instruction in the pipeline to stall, and it takes two cycles to execute that instruction\n"},{"title":"card_1506","front":"What is an example of pipeline stalls involving a jump?","back":"As another example of a pipeline stall, consider what happens when an instruction modifies the value in the EIP register. For example, the jnz (jump if not zero) instruction might change the value in the EIP register if it conditionally transfers control to its target label. This, of course, implies that the next set of instructions to be executed does not immediately follow the instruction that modifies EIP. By the time the instruction jnz completes execution (assuming the zero flag is clear, so that the branch is taken), we've already started five other instructions and we're only one clock cycle away from the completion of the first of these. Obviously, the CPU must not execute those instructions, or it will compute improper results. The only reasonable solution is to flush the entire pipeline and begin fetching opcodes anew. Doing so causes a severe execution-time penalty.\n"},{"title":"card_1507","front":"When does a control hazard occur?","back":"A control hazard occurs whenever the CPU branches to some new location in memory and consequently has to flush from the pipeline the instructions that are in various stages of execution.\n"},{"title":"card_1508","front":"When does a data hazard occur?","back":"Note that a data hazard occurs when the source operand of one instruction was a destination operand of a previous instruction.\n"},{"title":"card_1509","front":"What is special about a superscalar CPU?","back":"A superscalar CPU has several execution units. If it encounters in the prefetch queue two or more instructions that can execute independently, it will do so.\n"},{"title":"card_1510","front":"What is out-of-order execution?","back":"The CPU can execute instructions prior to the completion of instructions appearing previously in the code stream.\n"},{"title":"card_1511","front":"How can a CPU use more registers than it has?","back":"Register renaming is a sneaky way to give a CPU more registers than it actually has. Programmers will not have direct access to these extra registers, but the CPU can use them to prevent hazards in certain cases.\n"},{"title":"card_1512","front":"What is special about a VLIW system?","back":"In a VLIW computer system, the CPU fetches a large block of bytes (41 bits in the case of the IA-64 Itanium CPU) and decodes and executes this block all at once. This block of bytes usually contains two or more instructions (three in the case of the IA-64). VLIW computing requires the programmer or compiler to properly schedule the instructions in each block so that there are no hazards or other conflicts, but if properly scheduled, the CPU can execute three or more instructions per clock cycle.\n"},{"title":"card_1513","front":"What is SIMD and what does it do?","back":"In the SIMD (Single Instruction Multiple Data) model, the CPU executes a single instruction stream, just like the pure SISD model. However, in the SIMD model, the CPU operates on multiple pieces of data concurrently rather than on a single data object.\n\nAn SIMD version of add, would compute the sum of several values simultaneously. The Pentium III's MMX and SIMD instruction extensions, and the PowerPC's AltaVec instructions, operate in exactly this fashion. With the paddb MMX instruction, for example, you can add up to eight separate pairs of values with the execution of a single instruction.\n"},{"title":"card_1514","front":"How are MMX registers different from a general purpose register?","back":"MMX registers (MM0 and MM1) actually hold eight independent byte values (the MMX registers are 64 bits wide but are treated as eight 8-bit values rather than as a single 64-bit value)\n"},{"title":"card_1515","front":"What is MIMD?","back":"Multiple Instruction, Multiple Data\nIf you have a multiprogramming environment with multiple programs attempting to execute concurrently, the MIMD model does allow each of those programs to execute their own code stream simultaneously. This type of parallel system is called a multiprocessor system.\n"},{"title":"card_1516","front":"When does multiprocessing (running on multiple processors) not help you?","back":"Multiprocessing doesn't help a program's performance unless that program is specifically written for use on a multiprocessor system.\n"},{"title":"card_1517","front":"What is the cache-coherency problem?","back":"Multiple CPUs operating on the same object in memory. \nIn order for these two functions to operate properly, the two CPUs must notify each other whenever they make changes to shared objects, so the other CPU can update its local, cached copy.\n"},{"title":"card_1518","front":"What is hyper-threading?","back":"In a typical superscalar processor it is rare for an instruction sequence to utilize all the CPU's functional units on each clock cycle. Rather than allow those functional units to go unused, the CPU can run two separate threads of execution concurrently and keep all the CPU's functional units occupied. This allows a single CPU to, effectively, do the work of 1.5 CPUs in a typical multiprocessor system.\n"},{"title":"card_1519","front":"What is NUMA?","back":"NUMA, which stands for Non-Uniform Memory Access, is a bit of a misnomer. The term NUMA implies that different types of memory have different access times, and so it is descriptive of the entire memory hierarchy. \nA good example of NUMA memory is the memory on a video display card. Another example is flash memory, which has significantly slower access and transfer times than standard semiconductor RAM.\n"},{"title":"card_1520","front":"What is virtual memory?","back":"Most modern computer systems implement a virtual memory scheme that simulates main memory using a mass storage disk drive. A virtual memory subsystem is responsible for transparently copying data between the disk and main memory as needed by programs.\n"},{"title":"card_1521","front":"What is DSM?","back":"Distributed shared memory (DSM), where processes running on different computer systems share data stored in a common block of memory and communicate changes to that block across the network.\n"},{"title":"card_1522","front":"What are examples of offline storage?","back":"Magnetic tapes, disk cartridges, optical disks, and floppy diskettes.\n"},{"title":"card_1523","front":"What is the penalty for a main memory access? Why does it never take one cycle?","back":"If the program has to bring the data from main memory, 999 memory accesses later you're still paying an average cost of two clock cycles to access the data that Intel's documentation claims should happen in one cycle.\n"},{"title":"card_1524","front":"What is the clock timing penalty of an L2 access?","back":"Accessing data in the L2 cache is always slower than in the L1 cache, and there is always the equivalent of at least one wait state, and up to eight, when accessing data in the L2 cache.\n"},{"title":"card_1525","front":"How does L2 cache access help pay for itself?","back":"If you execute the mov(mem32,eax); instruction, and mem32's value is not in the L1 cache, the cache controller doesn't simply read mem32's 32 bits from the L2 cache, assuming that it's present there. Instead, the cache controller will actually read a whole block of bytes (generally 16, 32, or 64 bytes, depending on the particular processor) from the L2 cache.\n"},{"title":"card_1526","front":"How many bytes are there per cache line?","back":"Cache memory is usually organized in blocks of cache lines, with each line containing some number of bytes (typically a small power of two like 16, 32, or 64)\n"},{"title":"card_1527","front":"What is the relationship to cache lines to their alignment?","back":"Generally, if a cache line is n bytes long, that cache line will hold n bytes from main memory that fall on an n-byte boundary.\n"},{"title":"card_1528","front":"With 512 cache lines, how are the bits in the memory address used to map to a cache line and byte?","back":"8 KB cache with 512 16-byte cache lines and a 32-bit main-memory address. Because there are 512 cache lines, it requires 9 bits to select one of the cache lines (29 = 512). This example uses bits 4 through 12 to determine which cache line to use (assuming we number the cache lines from 0 to 511), while bits 0 through 3 of the original memory address determine the particular byte within the 16-byte cache line.\n"},{"title":"card_1529","front":"Why are fully associative caches generally not used?","back":"The extra circuitry to achieve full associativity is expensive and, worse, can slow down the memory subsystem.\n"},{"title":"card_1530","front":"Which type of caches are better for instructions, for code?","back":"In particular, the direct-mapped cache is very good for data that you access in a sequential rather than random fashion. Because the CPU typically executes instructions in a sequential fashion, instruction bytes can be stored very effectively in a direct-mapped cache. However, because programs tend to access data more randomly than code, a two-way or four-way set associative cache usually makes a better choice for data accesses than a direct-mapped cache.\n\nBecause data and machine instruction bytes usually have different access patterns, many CPU designers use separate caches for each.\n"},{"title":"card_1531","front":"What is temporal locality?","back":"If a memory location has not been accessed in a while, it is likely to be a long time before the CPU accesses it again.\n"},{"title":"card_1532","front":"What is a good replacement policy that many caching controllers use?","back":"The least recently used (LRU) algorithm.\n"},{"title":"card_1533","front":"What is write-through policy?","back":"The write-through policy states that any time data is written to the cache, the cache immediately turns around and writes a copy of that cache line to main memory.\n"},{"title":"card_1534","front":"What is a good cache write policy to use when two different CPUs are communicating through shared memory?","back":"Because the write-through policy updates main memory with the new value as rapidly as possible, it is a better policy to use when two different CPUs are communicating through shared memory.\n"},{"title":"card_1535","front":"What is a write-back policy?","back":"In this mode, writes to the cache are not immediately written to main memory; instead, the cache controller updates main memory at a later time. This scheme tends to be higher performance because several writes to the same cache line within a short time period do not generate multiple writes to main memory.\n"},{"title":"card_1536","front":"How does a cache keep track of data that needs to be written back to main memory?","back":"the cache controller usually maintains a dirty bit within each cache line. The cache system sets this bit whenever it writes data to the cache.\n"},{"title":"card_1537","front":"What does a cache controller have to do before it replaces a cache line with other data from memory?","back":"Whenever the cache controller replaces a cache line with other data from memory, it must first check the dirty bit, and if that bit is set, the controller must write that cache line to memory before going through with the cache-line replacement.\n"},{"title":"card_1538","front":"What has to be inherent in software in order for a cache system to be effective?","back":"In order for a cache system to be effective, software must exhibit locality of reference (either spatial or temporal). Fortunately, real-world programs tend to exhibit locality of reference, so most programs will benefit from the presence of a cache in the memory subsystem.\n"},{"title":"card_1539","front":"What are memory pages?","back":"You break up memory into blocks of bytes called pages. A page in main memory is comparable to a cache line in a cache subsystem, although pages are usually much larger than cache lines. For example, the 80x86 CPUs use a page size of 4,096 bytes.\n"},{"title":"card_1540","front":"How does the page table not take up cache space?","back":"To prevent cluttering the data or instruction cache with page-table entries, which increases the number of cache misses for data and instruction requests, the page table uses its own cache, known as the translation lookaside buffer (TLB).\n"},{"title":"card_1541","front":"How are the bits in a page table entry used?","back":"Each entry in the page table contains 32 bits, even though the system really only needs 20 bits to remap each virtual address to a physical address. Intel, on the 80x86, uses some of the remaining 12 bits to provide some memory-protection information.\n"},{"title":"card_1542","front":"How can your software change bits in the page table?","back":"Note that your applications do not have access to the page table (reading and writing the page table is the operating system's responsibility), and therefore they cannot modify these bits. However, operating systems like Windows may provide some functions you can call if you want to change certain bits in the page table (for example, Windows will allow you to set a page to read-only if you want to do so)\n"},{"title":"card_1543","front":"What is a working set?","back":"At any given time, a program will only access a small percentage of the pages in main memory that contain data and instruction bytes and this set of pages is known as the working set.\n"},{"title":"card_1544","front":"What happens when you attempt to access a page in memory?","back":"If you attempt to access a page of memory, and the page-table bit tells the memory management unit (MMU) that the page is not present in main memory, the CPU interrupts the program and passes control to the operating system.\n"},{"title":"card_1545","front":"How can you think of main memory?","back":"You can think of main memory as a fully associative write-back cache with 4,096-byte cache lines, which caches the data that is stored on the disk drive.\n"},{"title":"card_1546","front":"What are typical page sizes?","back":"Page sizes tend to vary from about 1 KB to 64 KB, depending on the CPU. For CPUs that support an address space larger than 4 GB, some CPUs use an inverted page table or a three-level page table.\n"},{"title":"card_1547","front":"What is the disadvantage of a program that does not exhibit locality of reference?","back":"Insufficient memory at a given level in the memory hierarchy to properly contain the program working sets of cache lines or pages.\n"},{"title":"card_1548","front":"What does the operating system do with the lowest addresses in memory allocated for a process?","back":"The operating system reserves the lowest memory addresses. Generally, your application cannot access data (or execute instructions) at the lowest addresses in memory. One reason the OS reserves this space is to help detect NULL pointer references.\n"},{"title":"card_1549","front":"What is binding?","back":"Binding is the process of associating an attribute with an object.\n"},{"title":"card_1550","front":"What are static objects?","back":"Static objects are those that have an attribute bound to them prior to the execution of the application. Constants are good examples of static objects; they have the same value bound to them throughout the execution of the application.\n"},{"title":"card_1551","front":"What is the lifetime of a static object?","back":"The lifetime of a static object extends from the point at which the program first begins execution to the point when the application terminates.\n"},{"title":"card_1552","front":"What is the scope of an identifier?","back":"The scope of an identifier is that section of the program where the identifier's name is bound to the object. As names exist only during compilation, scope is definitely a static attribute in compiled languages. (In interpretive languages, where the interpreter maintains the identifier names during program execution, scope can be a non-static attribute.)\n"},{"title":"card_1553","front":"What do you find in an executable file?","back":"In most executable files, you'll find a single section that combines the code, read-only data, and constant data sections.\n"},{"title":"card_1554","front":"What is the BSS section?","back":"The BSS section is where compilers typically put static objects that don't have an explicit value associated with them. BSS stands for block started by a symbol, which is an old assembly language term describing a pseudo-opcode one would use to allocate storage for an uninitialized static array. In modern OSes like Windows and Linux, the OS allows the compiler/linker to put all uninitialized variables into a BSS section that simply contains information that tells the OS how many bytes to set aside for the section.\n"},{"title":"card_1555","front":"What it the stack?","back":"The stack is a data structure that expands and contracts in response to procedure invocations and the return to calling routines, among other things. At run time, the system places all automatic variables (non-static local variables), subroutine parameters, temporary values, and other objects in the stack section of memory in a special data structure we call the activation record (which is aptly named because the system creates an activation record when a subroutine first begins execution, and it deallocates the activation record when the subroutine returns to its caller).\n"},{"title":"card_1556","front":"What is the different between a hardware stack and a software stack?","back":"If a CPU provides an explicit stack-pointer register (ESP), we say that the CPU supports a hardware stack; if only a general-purpose register is available, then we say that the CPU uses a software-implemented stack.\n"},{"title":"card_1557","front":"What are anonymous variables?","back":"We'll usually refer to objects in heap memory as anonymous variables because we refer to them by their memory address (via pointers) rather than by a name.\n"},{"title":"card_1558","front":"What is a simple heap manager implementation?","back":"Easy implementation of a heap manager that supports garbage collection. This simple system maintains a (linked) list of free memory blocks. Each free memory block in the list will require two double-word values: one double-word value specifies the size of the free block, and the other double word contains a link to the next free block in the list (that is, a pointer)\n"},{"title":"card_1559","front":"What are first-fit and best-fit?","back":"The first-fit algorithm does have a couple of advantages over the best-fit algorithm, though. The most obvious advantage is that the first-fit algorithm is usually faster. The best-fit algorithm has to scan through every block in the free block list in order to find the smallest block large enough to satisfy the allocation request\n"},{"title":"card_1560","front":"What is an advantage of first-fit in heap management?","back":"Another advantage to the first-fit algorithm is that it tends to suffer less from a degenerate condition known as external fragmentation. Fragmentation occurs after a long sequence of allocation and deallocation requests. Remember, when the heap manager satisfies a memory allocation request, it usually creates two blocks of memory — one in-use block for the request and one free block that contains the remaining bytes in the original block after the request is filled (assuming the heap manager did not find an exact fit). After operating for a while, the best-fit algorithm may wind up producing lots of smaller, leftover blocks of memory that are too small to satisfy an average memory request (because the best-fit algorithm also produces the smallest leftover blocks as a result of its behavior).\n"},{"title":"card_1561","front":"How does heap memory allocation optimize for speed?","back":"If an application calls the operating system for every memory request it makes, the performance of the application will probably suffer if the application makes several memory allocation and deallocation calls. OS API calls are very slow, because they generally involve switching between kernel mode and user mode on the CPU (which is not fast).\n\nOn the very first memory allocation, the malloc routine will request a large block of memory from the operating system, and then the application's malloc and free routines will manage this block of memory themselves.\n"},{"title":"card_1562","front":"What is allocation granularity?","back":"Although most heap managers will allow you to allocate storage in blocks as small as one byte, most memory managers will actually allocate some minimum number of bytes greater than one. This minimum amount is the allocation granularity the memory manager supports.\n"},{"title":"card_1563","front":"What is the usual allocation alignment?","back":"For performance reasons, many heap managers begin each allocation on a typical cache-line boundary, usually 16, 32, or 64 bytes.\n"},{"title":"card_1564","front":"How is internal fragmentation somewhat avoided?","back":"The granularity size is quite small for most memory managers (typically 16 bytes or fewer), so after thousands and thousands of memory allocations you'll only lose a couple dozen or so kilobytes to internal fragmentation.\n"},{"title":"card_1565","front":"What is a problem with allocation on the heap of many small objects?","back":"If you allocate lots of small objects, the memory consumed by internal fragmentation and control information (meta information stored with each heap block) may represent a significant portion of your heap area.\n"},{"title":"card_1566","front":"How are I/O operations similar to memory read and write operations?","back":"I/O operations behave much like memory read and write operations, except that there are usually more wait states associated with I/O operations.\n"},{"title":"card_1567","front":"What does an output port typically use to hold data to be sent to the outside world?","back":"An output port typically uses a latch device to hold data to be sent to the outside world.\n"},{"title":"card_1568","front":"What are the read or write abilities of an output port?","back":"Output ports can be write-only or read/write.\n"},{"title":"card_1569","front":"What must be active for a latch to operate?","back":"Both the address decode line (En) and the write control line (W) must be active for the latch to operate.\n"},{"title":"card_1570","front":"What does the CPU read from a read/write port?","back":"Whenever the CPU reads data from a read/write port, it reads the data that was last written to the port allowing a programmer to retrieve that value.\n"},{"title":"card_1571","front":"What is a dual I/O port?","back":"A dual I/O port is also a read/write port, but when you read a dual I/O port, you read data from an external input device rather than the last data written to the output side of the port's address.\n"},{"title":"card_1572","front":"What is a dual I/O port composed of?","back":"Note that a dual I/O port is actually created using two ports — a read-only port and a write-only port — that share the same port address.\n"},{"title":"card_1573","front":"What is a bidirectional port?","back":"A bidirectional port allows the CPU to both read and write data to an external device. To function properly, a bidirectional port must pass various control lines, such as read and write enable, to the peripheral device so that the device can change the direction of data transfer based on the CPU's read/write request. In effect, a bidirectional port is an extension of the CPU's bus through a bidirectional latch or buffer.\n"},{"title":"card_1574","front":"What is memory-mapped I/O?","back":"Memory-mapped I/O uses ordinary locations within the CPU's memory address space to communicate with peripheral devices.\n"},{"title":"card_1575","front":"What is I/O-mapped input/output?","back":"I/O-mapped input/output uses an address space separate from memory, and it uses special machine instructions to transfer data between that special I/O address space and the outside world.\n"},{"title":"card_1576","front":"What is DMA?","back":"DMA is a special form of memory-mapped I/O where the peripheral device reads and writes data located in memory without CPU intervention\n"},{"title":"card_1577","front":"How does a memory-mapped peripheral device work?","back":"A memory-mapped peripheral device is connected to the CPU's address and data lines exactly like regular memory, so whenever the CPU writes to or reads from the address associated with the peripheral device, the CPU transfers data to or from the device.\n"},{"title":"card_1578","front":"How do some video cards handle their memory?","back":"Some video cards have 32 MB of on-board memory that they map into the memory address space and this means that the 32 MB address range consumed by the card is not available to the system for use as regular RAM memory.\n"},{"title":"card_1579","front":"Does the CPU cache values for memory-mapped I/O ports?","back":"No. The CPU cannot cache values intended for memory-mapped I/O ports.\n"},{"title":"card_1580","front":"How can a programmer get access to I/O address space?","back":"As almost all high-level languages provide the ability to access memory, but most do not allow access to the I/O space, having the PCI bus remap the I/O address space into the memory address space provides I/O access to those high-level languages.\n"},{"title":"card_1581","front":"What is direct memory access and its advantage in timely processing?","back":"For very high-speed I/O devices the CPU may be too slow to process this data one byte (or one word or double word) at a time. Such devices generally have an interface to the CPU's bus so they can directly read and write memory, which is known as direct memory access because the peripheral device accesses memory directly, without using the CPU as an intermediary.\n"},{"title":"card_1582","front":"What is a medium-speed device?","back":"Devices that transfer data at approximately the same rate as, or up to two orders of magnitude slower than, the CPU.\n"},{"title":"card_1583","front":"What are high-speed devices?","back":"Devices that transfer data faster than the CPU is capable of handling using programmed I/O. High-speed devices must use DMA because programmed I/O is too slow.\n"},{"title":"card_1584","front":"What I/O mechanisms do medium and low-speed devices use?","back":"Medium- and low-speed devices may use any of the three I/O mechanisms for data transfer (though low-speed devices rarely use DMA because of the cost of the extra hardware involved).\n"},{"title":"card_1585","front":"How do I/O devices communicate with the interrupt controller?","back":"Most peripheral buses provide a common set of interrupt control signals that let I/O devices communicate directly with the system's interrupt controller, which is also a peripheral device.\n"},{"title":"card_1586","front":"What must a CPU do if it wishes to access a peripheral on the PCI bus?","back":"Whenever the CPU wishes to access a peripheral on the PCI bus, it must negotiate with other peripheral devices for the right to use the bus. This negotiation can take several clock cycles before the PCI controller grants the CPU access to the bus.\n"},{"title":"card_1587","front":"What is called when the CPU receives an interrupt?","back":"interrupt service routine (ISR)\n"},{"title":"card_1588","front":"What can be used to make I/O ports accessible from user applications?","back":"It is possible to use the Linux ioperm system call to make certain I/O ports accessible from user applications.\n"},{"title":"card_1589","front":"How does the OS save reads when writing full blocks to disk?","back":"If your block size is 4,096 bytes, but you just write 2,000 bytes to some block and then seek to some other position in the file outside that block, the OS will actually have to read the entire 4,096-byte block from the disk, merge in the 2000 bytes, and then finally write the entire 4,096 bytes back to the disk. This happens because the OS must read and write entire blocks; it cannot transfer partial blocks between the disk and memory. Contrast this with a write operation that writes a full 4,096 bytes — in this case, the OS wouldn't have to read the data from the disk first; it would only have to write the block.\n"},{"title":"card_1590","front":"What are memory-mapped files?","back":"Memory-mapped files use the OS's virtual memory capabilities to map memory addresses in the application space directly to blocks on the disk. Because modern OSes have highly optimized virtual memory subsystems, piggy-backing file I/O on top of the virtual memory subsystem can produce very efficient file access.\n"},{"title":"card_1591","front":"What is a drawback of memory-mapped files?","back":"Almost every OS does memory-mapped file access differently, and there is little chance that memory-mapped file I/O code will be portable between OSes.\n"},{"title":"card_1592","front":"What is LSD radix sort?","back":"Least Significant Digit first radix sort. It doesn't have to be a digit, just a symbol in an alphabet. Sorts stably from right to left.\n"},{"title":"card_1593","front":"What is MSD radix sort?","back":"Most Significant Digit first radix sort. It doesn't have to be a digit, just a symbol in an alphabet. Sorts stably from left to right, recursing when the symbols in a block equal each other.\n"},{"title":"card_1594","front":"What is the time complexity of using a trie to store patterns, then testing that trie against a string, looking for matches?","back":"O(|string| * |len of longest pattern|)\n"},{"title":"card_1595","front":"What is the time complexity for generating a suffix trie?","back":"O(|text|)\n"},{"title":"card_1596","front":"What can you do with a suffix trie to generate a suffix array?","back":"DFS the trie to get a list of suffixes.\n"},{"title":"card_1597","front":"What is the algorithm called that generates a suffix array in linear time?","back":"Manber-Myers\n"},{"title":"card_1598","front":"What are 2 disadvantages of MSD radix sort?","back":"- cache inefficient\n- lot of work in an inner loop\n"},{"title":"card_1599","front":"What type of input does MSD radix sort do best on?","back":"when the data to be sorted seems random\n\nwhen the data is very similar, it can come to linear time work, which is slow for MSD\n"},{"title":"card_1600","front":"What is the runtime of KMP?","back":"O(|P| + |T|)\n"},{"title":"card_1601","front":"What operations is a trie efficient on?","back":"- longest prefix\n- wild card at beginning\n- wild card at end\n"},{"title":"card_1602","front":"When making a trie node, what is the typical implementation of the children?","back":"An array of size R (the radix or alphabet size) with a pointer to continuing paths. Paths that do not continue have null stored in the array indexes for those paths.\n"},{"title":"card_1603","front":"When searching for a match in string with length N and pattern length M, where should we stop to ensure we don't look for matches at the end that would be too short?","back":"i <= n - m\n"},{"title":"card_1604","front":"What does the preprocessing step of KMP do?","back":"Builds a DFA (deterministic finite automaton) of the pattern to be searched.\n"},{"title":"card_1605","front":"What is the size needed for the DFA created by KMP during its preprocessing step?","back":"O(R * M)\n- r is the radix\n- m is the length of the pattern\n"},{"title":"card_1606","front":"What is the runtime of the preprocessing step for Boyer-Moore?","back":"O(|P|)\n\n- P is the pattern\n"},{"title":"card_1607","front":"What is the expected runtime of Boyer-Moore?","back":"O(n/m)\n\n- n is the length of the text\n- m is the length of the pattern\n"},{"title":"card_1608","front":"What is the mathematical method called that allows Rabin-Karp to be efficient?","back":"Horner's method\n"},{"title":"card_1609","front":"What is Kleene's theorem?","back":"It states that any regular language (regular expression) is accepted by an FA and conversely that any language accepted by an FA is regular.\n"},{"title":"card_1610","front":"What is the difference between a DFA and an NFA?","back":"DFA can have only one applicable transition per character.\nNFA can have several applicable transitions.\n"},{"title":"card_1611","front":"What is the behavior of a greedy strategy?","back":"A greedy strategy usually progresses in a top-down order, making one greedy choice after another and reducing each given problem instance to a smaller one.\n"},{"title":"card_1612","front":"What are 2 properties of an interview problem with a potential dynamic programming solution?","back":"If an interview problem has optimal substructure and overlapping subproblems, it might be solved by dynamic programming.\n"},{"title":"card_1613","front":"What is backtracking?","back":"Backtracking is a refinement of the brute-force approach, which systematically searches for a solution to a problem among all available options. It is suitable for scenarios where there is a set of options available at each step, and we must choose one from these. After a choice is made, there is a new set of options for the next step. This procedure is repeated over and over until we reach a final state.\n"},{"title":"card_1614","front":"How does a backtracking algorithm behave?","back":"The backtracking algorithm traverses this tree recursively, from the root down and in depth-first order. When it reaches a leaf that corresponds to a non-acceptable state, it backtracks to continue the search for another leaf by revoking the most recent choice and tries out the next option. If it runs out of options, it revokes again and tries another choice at that node. If it ends up at the root with no options left, there are no acceptable states to be found.\n"},{"title":"card_1615","front":"How do Python's encode and decode methods work?","back":"To convert Unicode characters to binary data, you must use the encode method. To convert binary data to Unicode characters, you must use the decode method.\n"},{"title":"card_1616","front":"How can you interpret a string in Python as an integer with a base other than 10?","back":"The integer constructor, int(), by default, the string must use base 10. If conversion from a different base is desired, that\nbase can be indicated as a second, optional, parameter. For example, the expression int(7f, 16) evaluates to the integer 127.\n"},{"title":"card_1617","front":"What does Patricia in a Patricia trie stand for?","back":"PATRICIA: practical algorithm to retrieve information coded in alphanumeric\n"},{"title":"card_1618","front":"What is the ordering relationship in a sequence in Python?","back":"The list, tuple, and str classes are sequence types in Python, representing a collection of values in which the order is significant.\n"},{"title":"card_1619","front":"How can you copy a list in Python?","back":"Because an existing list is itself iterable, the syntax backup = list(data) can be used to construct a new list instance referencing the same contents as the original.\n"},{"title":"card_1620","front":"How can you represent a 1-element tuple?","back":"(17,) is a one-element tuple\n"},{"title":"card_1621","front":"How can you make long, multi-line string literal in Python?","back":"Python supports using the delimiter or \"\"\" to begin and end a string literal.\n"},{"title":"card_1622","front":"What types of objects can be added to a Python set?","back":"Only instances of immutable types can be added to a Python set, since they are used as hash keys.\n"},{"title":"card_1623","front":"How can you represent an empty set in Python?","back":"The constructor syntax set() produces an empty set.\n"},{"title":"card_1624","front":"How can you initialize a Python dictionary with values already declared elsewhere?","back":"The constructor accepts a sequence of key-value pairs as a parameter, as in dict(pairs) with:\npairs = [('ga', 'Irish'), ('de', 'German')].\n"},{"title":"card_1625","front":"How can you tell that two Python objects are the same object?","back":"The expression a is b evaluates to True, precisely when identifiers a and b are aliases for the same object.\n"},{"title":"card_1626","front":"What is the division rule in Python?","back":"Python guarantees that q*d + r will equal n.\nd = denominator\nq = quotient\nr = remainder\nn = numerator\n"},{"title":"card_1627","front":"How do you express a set intersection in Python?","back":"s1 & s2 the intersection of s1 and s2\n"},{"title":"card_1628","front":"How do you represent a set union in Python?","back":"s1 | s2 the union of s1 and s2\n"},{"title":"card_1629","front":"In Python, how can you get the set of elements in s1 but not s2?","back":"s1 − s2\n"},{"title":"card_1630","front":"In Python, how can you get the set of elements in precisely one of s1 or s2?","back":"s1 ˆ s2\n"},{"title":"card_1631","front":"How can you test that two dictionaries contain the same set of key-value pairs?","back":"Dictionaries support the notion of equivalence, with d1 == d2 if the two dictionaries contain the same set of key-value pairs.\n"},{"title":"card_1632","front":"In Python, how can you extend a list with two more elements? (adding to the original list, not making a new one)","back":"beta += [4, 5]\n"},{"title":"card_1633","front":"In Python, how do you reassign a list beta to a new list [1, 2, 3, 4, 5, 6, 7]? (making a new object instead of adding to the original)","back":"beta = beta + [6, 7]\n"},{"title":"card_1634","front":"How does an expression like 1 <= x + y <= 10 save computation?","back":"The expression 1 <= x + y <= 10 is evaluated as the compound (1 <= x + y) and (x + y <= 10), but without computing the intermediate value x + y twice.\n"},{"title":"card_1635","front":"What happens when you call a Python function?","back":"Each time a function is called, Python creates a dedicated activation record that stores information relevant to the current call. This activation record includes what is known as a namespace to manage all identifiers that have local scope within the current call.\n"},{"title":"card_1636","front":"How does Python support polymorphism, method overloading?","back":"Python provides means for functions to support more than one possible calling signature using default parameter values. Such a function is said to be polymorphic.\n"},{"title":"card_1637","front":"What is the rule for default parameters in Python?","back":"It is illegal to define a function with a signature such as bar(a, b=15, c) with b having a default value, yet not the subsequent c; if a default parameter value is present for one parameter, it must be present for all further parameters.\n"},{"title":"card_1638","front":"What kind of exception is raised in an attempt to access a nonexistent element from a set or dictionary?","back":"KeyError\n"},{"title":"card_1639","front":"What kind of exception is raised on a sequence when syntax such as data[k] is used with an integer k that is not a valid index for the given sequence?","back":"IndexError\n"},{"title":"card_1640","front":"How can you test that a function parameter x is of type int or float?","back":"if not isinstance(x, (int, float)):\n"},{"title":"card_1641","front":"When should you use try/except?","back":"The try-except clause is best used when there is reason to believe that the exceptional case is relatively unlikely, or when it is prohibitively expensive to proactively evaluate a condition to avoid the exception.\n"},{"title":"card_1642","front":"How can you catch an exception of more than one type?","back":"except (ValueError, EOFError):\n"},{"title":"card_1643","front":"How can you catch a Python exception, handle it, and then re-raise the exception?","back":"except EOFError: \n print( There was an unexpected error reading input. ) \n raise\n"},{"title":"card_1644","front":"Can you use return and yield together?","back":"It is illegal to combine yield and return statements in the same implementation, other than a zero-argument return statement to cause a generator to end its execution.\n"},{"title":"card_1645","front":"Can you define a tuple without parentheses?","back":"Yes:\ndata = 2, 4, 6, 8\n"},{"title":"card_1646","front":"How can you get a list of variables in the local namespace?","back":"Calls to dir() and vars() report on the most locally enclosing namespace in which they are executed\n"},{"title":"card_1647","front":"What are first-class objects?","back":"First-class objects are instances of a type that can be assigned to an identifier, passed as a parameter, or returned by a function.\n"},{"title":"card_1648","front":"What does Python's sys module do?","back":"Provides additional level of interaction with the Python interpreter.\n"},{"title":"card_1649","front":"What does Python's os module do?","back":"Provides support for interactions with the operating system.\n"},{"title":"card_1650","front":"What is the significance of using a seed value?","back":"The sequence of numbers generated for a given seed will always be the same.\n"},{"title":"card_1651","front":"What is an object?","back":"An instance of a class.\n"},{"title":"card_1652","front":"What is the convention for non-public data members and member functions in Python?","back":"By convention, names of members of a class (both data members and member functions) that start with a single underscore character (e.g., _secret) are assumed to be nonpublic and should not be relied upon.\n"},{"title":"card_1653","front":"Python provides an automatic iterator implementation for any class that implements what two methods?","back":"__len__ and __getitem__\n"},{"title":"card_1654","front":"What is the type of evaluation that range() uses?","back":"It uses a strategy known as lazy evaluation.\n"},{"title":"card_1655","front":"What is the formula for the number of elements in the range?","back":"max(0, (stop − start + step − 1) // step)\n"},{"title":"card_1656","front":"How can you call super in a constructor?","back":"super().__init__(arg1, arg2)\n"},{"title":"card_1657","front":"What is the template method pattern?","back":"The template method pattern is when an abstract base class provides concrete behaviors that rely upon calls to other abstract behaviors.\n\nThe template method pattern describes a generic computation mechanism that can be specialized for a particular application by redefining certain steps. To allow customization, the primary algorithm calls auxiliary functions known as hooks at designated steps of the process.\n"},{"title":"card_1658","front":"How can you define a class constant in Python?","back":"class PredatoryCreditCard(CreditCard): \n OVERLIMIT FEE = 5\n"},{"title":"card_1659","front":"What is an important caveat of __slots__ in an inheritance hierarchy?","back":"When inheritance is used, if the base class declares __slots__, a subclass must also declare __slots__ to avoid creation of instance dictionaries. The declaration in the subclass should only include names of supplemental methods that are newly introduced.\n"},{"title":"card_1660","front":"What is dynamic dispatch?","back":"Python uses what is known as dynamic dispatch (or dynamic binding) to determine, at run-time, which implementation of a function to call based upon the type of the object upon which it is invoked.\n"},{"title":"card_1661","front":"What is static dispatching?","back":"Making a compile-time decision as to which version of a function to call, based upon the declared type of a variable.\n"},{"title":"card_1662","front":"What is the total of sum(1 + 2 + 4 + 8 + · · · + 2^(n−1)) ?","back":"2^n − 1\n"},{"title":"card_1663","front":"What is the definition of Big-O (upper bound)?","back":"We say that f(n) is O(g(n)) if there is a real constant c > 0 and an integer constant n0 ≥ 1 such that f(n) ≤ cg(n), for n ≥ n0.\n"},{"title":"card_1664","front":"How can you get a string of letters from another string, using only the alphanumeric (one-liner)?","back":"letters = ''.join(c for c in document if c.isalpha())\n"},{"title":"card_1665","front":"In Python, how can you get ['b', 'i', 'r', 'd'] from \"bird\"?","back":"list(bird)\n"},{"title":"card_1666","front":"How can you get a value in a list of length 26, with index i rotated r positions to the right?","back":"(i + r) mod 26\n"},{"title":"card_1667","front":"How can you get the ASCII distance from A of a character c?","back":"j = ord(c) − ord('A')\n"},{"title":"card_1668","front":"Describe the adapter design pattern.","back":"The adapter design pattern applies to any context where we effectively want to modify an existing class so that its methods match those of a related, but different, class or interface.\n"},{"title":"card_1669","front":"What data structure can be used to reverse a sequence?","back":"As a consequence of the LIFO protocol, a stack can be used as a general tool to reverse a data sequence.\n"},{"title":"card_1670","front":"When using a circular array queue, when we dequeue an element and want to \"advance\" the front index, what is the arithmetic for computing the front of the queue f?","back":"f = (f + 1) % N\n"},{"title":"card_1671","front":"What is the drawback of amortized bounds?","back":"Amortized bounds for operations may be unacceptable in real-time systems.\n"},{"title":"card_1672","front":"Describe briefly the composition pattern?","back":"We define a single object that is composed of two or more other objects.\n"},{"title":"card_1673","front":"What is another name for a heuristic?","back":"A rule of thumb.\n"},{"title":"card_1674","front":"What is a benefit of data accesses for arrays?","back":"Arrays provide O(1)-time access to an element based on an integer index.\n"},{"title":"card_1675","front":"Operations with equivalent asymptotic bounds typically run a constant factor more efficiently with an _____-based structure versus a _____ structure.","back":"array\nlinked\n"},{"title":"card_1676","front":"______-based representations typically use proportionally less memory than _______ structures.","back":"array\nlinked\n"},{"title":"card_1677","front":"______-based structures provide worst-case time bounds for their operations.","back":"link\n"},{"title":"card_1678","front":"_______-based structures support O(1)-time insertions and deletions at arbitrary positions.","back":"link\n"},{"title":"card_1679","front":"How can u be an ancestor of v?","back":"A node u is an ancestor of a node v if u = v or u is an ancestor of the parent of v.\n"},{"title":"card_1680","front":"What does an ordered tree mean?","back":"A tree is ordered if there is a meaningful linear order among the children of each node.\n"},{"title":"card_1681","front":"What is a proper binary tree?","back":"A binary tree is proper if each node has either zero or two children.\n"},{"title":"card_1682","front":"How many nodes are in a tree of height d?","back":"In a binary tree, level 0 has at most one node (the root), level 1 has at most two nodes (the children of the root), level 2 has at most four nodes, and so on. In general, level d has at most 2^d nodes.\n"},{"title":"card_1683","front":"What is a drawback of an array representation of trees?","back":"Some update operations for trees cannot be efficiently supported. For example, deleting a node and promoting its child takes O(n) time because it is not just the child that moves locations within the array, but all descendants of that child.\n"},{"title":"card_1684","front":"What is the bounds on the height of a binary tree of n nodes?","back":"as small as log(n + 1) − 1\nas large as n − 1\n"},{"title":"card_1685","front":"What are the time complexities of locating the last position of a heap, as required for add and remove min, in an array representation or tree representation?","back":"Locating the last position of a heap, as required for add and remove min, can be performed in O(1) time for an array-based representation, or O(log n) time for a linked-tree representation.\n"},{"title":"card_1686","front":"A heap is a complete binary tree with every level being full. What is it's height?","back":"h = log(n + 1) − 1\n"},{"title":"card_1687","front":"What is the time complexity to produce a list of the k largest values from an iterable, using a heap?","back":"O(n + k log n)\nn: heapify\nk: accesses\nlog n: cost per access\n"},{"title":"card_1688","front":"What is a strict weak order?","back":"It allows for keys to be considered equal to each other.\n"},{"title":"card_1689","front":"How you can read a file and get the unique words from a file?","back":"for piece in open(filename).read().lower().split():\n"},{"title":"card_1690","front":"What are some good numbers to hash with character strings that are English words, to create a good hash?","back":"33, 37, 39, and 41\n"},{"title":"card_1691","front":"What is the standard mechanism for computing hash codes in Python?","back":"A built-in function with signature hash(x) that returns an integer value that serves as the hash code for object x.\n"},{"title":"card_1692","front":"How can you implement a hash for your user-defined class in Python?","back":"def __hash__(self):\n return hash( (self. red, self. green, self. blue) ) # hash combined tuple\n"},{"title":"card_1693","front":"What is the second action performed as part of an overall hash function called that fits the hash into the storage space?","back":"compression function\n"},{"title":"card_1694","front":"What is the caveat for choosing a prime for N for your hash table size?","back":"Choosing N to be a prime number is not always enough, for if there is a repeated pattern of hash codes of the form p*N + q for several different p's, then there will still be collisions.\n"},{"title":"card_1695","front":"What is MAD and what is its formula?","back":"Multiply-Add-and-Divide\n[(a*i + b) mod p] mod N\n"},{"title":"card_1696","front":"What is the rule of thumb when coming up with the right load factor?","back":"The ratio λ = n/N, called the load factor of the hash table, should be bounded by a small constant, preferably below 1. As long as λ is O(1), the core operations on the hash table run in O(1) expected time.\n"},{"title":"card_1697","front":"What does open addressing require?","back":"Open addressing requires that the load factor is always at most 1 and that items are stored directly in the cells of the bucket array itself.\n"},{"title":"card_1698","front":"What is quadratic probing?","back":"Another open addressing strategy that iteratively tries the buckets A[(h(k) + f (i)) mod N], for i = 0,1,2, . . ., where f(i) = i^2, until finding an empty bucket.\n"},{"title":"card_1699","front":"What does quadratic probing suffer from?","back":"It creates its own kind of clustering, called secondary clustering, where the set of filled array cells still has a non-uniform pattern, even if we assume that the original hash codes are distributed uniformly.\n"},{"title":"card_1700","front":"What is the double hashing strategy?","back":"In this approach, we choose a secondary hash function, h', and if h maps some key k to a bucket A[h(k)] that is already occupied, then we iteratively try the buckets A[(h(k) + f(i)) mod N] next, for i = 1,2,3, . . where f(i) = i * h\u0002'(k).\nIn this scheme, the secondary hash function is not allowed to evaluate to zero; a common choice is h\u0002(k) = q−(k mod q), for some prime number q < N. Also, N should be a prime.\n"},{"title":"card_1701","front":"What is the optimal load factor for hashing using separate chaining?","back":"λ < 0.9\n"},{"title":"card_1702","front":"What is the optimal load factor for hashing using linear probing?","back":"λ < 0.5\n"},{"title":"card_1703","front":"What is the load factor of Python's implementation of hash tables?","back":"λ < 2/3\n"},{"title":"card_1704","front":"What is a sorted table implementation of a hash table best suited for?","back":"Sorted tables are primarily used in situations where we expect many searches but relatively few updates.\n"},{"title":"card_1705","front":"The O(log n) time bounds for skip lists extend to what operations over a sorted list?","back":"The skip list has the same logarithmic time bounds for searching as is achieved by the binary search algorithm, yet it extends that performance to update methods when inserting or deleting items. Nevertheless, the bounds are expected for the skip list, while binary search has a worst-case bound with a sorted table.\n"},{"title":"card_1706","front":"How does a skip list compare to an AVL tree or other balanced search trees?","back":"Optimized skip lists are faster in practice than AVL trees and other balanced search trees.\n"},{"title":"card_1707","front":"What are skip lists a simple implementation of?","back":"Skip lists provide a simple implementation of a sorted map.\n"},{"title":"card_1708","front":"What is the worst-case running time for performing the __getitem__, __setitem__, and __delitem__ map operations in a skip list S with n entries and height h?","back":"O(n + h)\n"},{"title":"card_1709","front":"What is the height of a skip list S with n items with high probability?","back":"O(log n)\n"},{"title":"card_1710","front":"What is a bag?","back":"A multiset (also known as a bag) is a set-like container that allows duplicates.\n"},{"title":"card_1711","front":"What is a multiset?","back":"A multiset (also known as a bag) is a set-like container that allows duplicates.\n"},{"title":"card_1712","front":"What is a multimap?","back":"A multimap is similar to a traditional map, in that it associates values with keys; however, in a multimap the same key can be mapped to multiple values. For example, the index of this book maps a given term to one or more locations at which the term occurs elsewhere in the book.\n"},{"title":"card_1713","front":"How can you create an instance of the class you're in?","back":"thing = type(self)()\n"},{"title":"card_1714","front":"What is a way to implement a multiset?","back":"A way to implement a multiset is by using a map in which the map key is a (distinct) element of the multiset, and the associated value is a count of the number of occurrences of that element within the multiset.\n"},{"title":"card_1715","front":"What is a predecessor?","back":"Return the position containing the greatest key that is less than that of position p (i.e., the position that would be visited immediately before p in an inorder traversal)\n"},{"title":"card_1716","front":"What is a successor?","back":"The position containing the least key that is greater than that of position p (i.e., the position that would be visited immediately after p in an inorder traversal)\n"},{"title":"card_1717","front":"What is an example of the factory method design pattern?","back":"We provide a subclass the means to control the type of node that is created within methods of the parent class, by inheriting and augmenting.\n"},{"title":"card_1718","front":"What is the special property of AVL trees?","back":"Height-Balance Property: For every position p of T, the heights of the children of p differ by at most 1.\n"},{"title":"card_1719","front":"What does AVL stand for?","back":"Adel'son-Vel'skii and Landis\n"},{"title":"card_1720","front":"What is the maximum height of an AVL tree storing n entries?","back":"At most 2 log n + 2\n"},{"title":"card_1721","front":"What is special about the self-balancing property of a splay tree?","back":"A splay tree does not strictly enforce a logarithmic upper bound on the height of the tree. In fact, there are no additional height, balance, or other auxiliary data associated with the nodes of this tree.\n"},{"title":"card_1722","front":"Why is splaying vital to the self-balancing property of a splay tree?","back":"Splaying allows us to guarantee a logarithmic amortized running time, for insertions, deletions, and searches.\n"},{"title":"card_1723","front":"How does a red-black tree relate to a (2,4) tree?","back":"Given a red-black tree, we can construct a corresponding (2,4) tree by merging every red node w into its parent, storing the entry from w at its parent, and with the children of w becoming ordered children of the parent.\n"},{"title":"card_1724","front":"What is the time complexity advantage of a red-black tree?","back":"The primary advantage of a red-black tree is that an insertion or deletion requires only a constant number of restructuring operations.\n"},{"title":"card_1725","front":"What is the floor?","back":"the floor of x, that is, the largest integer k, such that k ≤ x\n"},{"title":"card_1726","front":"What is the ceiling?","back":"the ceiling of x, that is, the smallest integer m, such that x ≤ m\n"},{"title":"card_1727","front":"What is the running time of merge?","back":"O(len(n1) + len(n2))\n"},{"title":"card_1728","front":"What is bottom-up merge sort?","back":"The main idea is to perform merge-sort bottom-up, performing the merges level by level going up the merge-sort tree. Given an input array of elements, we begin by merging every successive pair of elements into sorted runs of length two. We merge these runs into runs of length four, merge these new runs into runs of length eight, and so on, until the array is sorted.\n"},{"title":"card_1729","front":"What is the worst-case lower bound on comparison-based sorting?","back":"Comparison-based sorting has an Ω(n log n) worst-case lower bound on its running time.\n"},{"title":"card_1730","front":"What is the optimal relationship of range N of keys to sequence size n in bucket sort?","back":"Bucket-sort is efficient when the range N of values for the keys is small compared to the sequence size n, say N = O(n) or N = O(n log n). Still, its performance deteriorates as N grows compared to n.\n"},{"title":"card_1731","front":"What is the rule of thumb in sorting on 2 or more columns across a stable sort?","back":"By first stably sorting by the second component and then again by the first component, we guarantee that if two entries are equal in the second sort (by the first component), then their relative order in the starting sequence (which is sorted by the second component) is preserved.\n"},{"title":"card_1732","front":"What is the time complexity of radix sort across d keys of size N?","back":"Let S be a sequence of n key-value pairs, each of which has a key (k1,k2, . . . ,kd), where ki is an integer in the range [0,N − 1] for some integer N ≥ 2. We can sort S lexicographically in time O(d(n + N)) using radix-sort.\n"},{"title":"card_1733","front":"What is the running time of insertion-sort on n items where m is the number of inversions (the number of pairs of elements out of order)?","back":"O(n + m)\n"},{"title":"card_1734","front":"In what case does insertion sort beat quicksort or merge sort?","back":"For sorting sequences that are already “almost” sorted.\n"},{"title":"card_1735","front":"Is heap sort stable?","back":"No. A standard heap-sort does not provide a stable sort, because of the swapping of elements.\n"},{"title":"card_1736","front":"Even though it's O(n^2)-time worst-case performance makes quicksort susceptible in real-time applications, what can we expect of its performance?","back":"We expect its performance to be O(n log n)-time, and experimental studies have shown that it outperforms both heap-sort and merge-sort on many tests.\n"},{"title":"card_1737","front":"What is the shining using case of merge sort?","back":"Merge-sort is an excellent algorithm for situations where the input is stratified across various levels of the computer's memory hierarchy (e.g., cache, main memory, external memory). In these contexts, the way that merge-sort processes runs of data in long merge streams makes the best use of all the data brought as a block into a level of memory, thereby reducing the total number of memory transfers.\n"},{"title":"card_1738","front":"What is Timsort and why is it a great sorting algorithm?","back":"Tim-sort (designed by Tim Peters), which is essentially a bottom-up merge-sort that takes advantage of some initial runs in the data while using insertion-sort to build additional runs.\n"},{"title":"card_1739","front":"How can you sort a sequence of strings by their length?","back":"foo.sort(key=len)\nor\nsorted(foo, key=len)\n"},{"title":"card_1740","front":"What design pattern does Python use with the key parameter when sorting?","back":"decorate-sort-undecorate\n"},{"title":"card_1741","front":"What are order statistics?","back":"Queries that ask for an element with a given rank.\n"},{"title":"card_1742","front":"What is prune-and-search or decrease-and-conquer?","back":"We solve a given problem that is defined on a collection of n objects by pruning away a fraction of the n objects and recursively solving the smaller problem.\n"},{"title":"card_1743","front":"When generating a Huffman code, what is an important restriction on the encoding for each element?","back":"In order to avoid ambiguities, we insist that no code-word in our encoding be a prefix of another code-word in our encoding. Such a code is called a prefix code, and it simplifies the decoding of Y to retrieve X.\n"},{"title":"card_1744","front":"What is the time complexity when Huffman’s algorithm constructs an optimal prefix code for a string of length n with d distinct characters?","back":"O(n + d log d)\n"},{"title":"card_1745","front":"What is the greedy-choice property?","back":"This is the property that a global optimal condition can be reached by a series of locally optimal choices (that is, choices that are each the current best from among the possibilities available at the time), starting from a well-defined starting condition.\n"},{"title":"card_1746","front":"What is the use case when preprocessing a text is worth it?","back":"Where a series of queries is performed on a fixed text, so that the initial cost of preprocessing the text is compensated by a speedup in each subsequent query.\n"},{"title":"card_1747","front":"What is the main application for tries?","back":"information retrieval\n"},{"title":"card_1748","front":"What are the primary query operations that tries support?","back":"pattern matching and prefix matching\n"},{"title":"card_1749","front":"What solves the space inefficiency in the standard trie?","back":"Compressed trie, which is also known (for historical reasons) as the Patricia trie.\n"},{"title":"card_1750","front":"What is the advantage of a compressed trie over a standard trie?","back":"The number of nodes of the compressed trie is proportional to the number of strings and not to their total length.\n"},{"title":"card_1751","front":"What is a suffix trie (also known as a suffix tree or position tree) of string X?","back":"The case when the strings in the collection S are all the suffixes of a string X.\n"},{"title":"card_1752","front":"How does a suffix trie save space over a list of all suffixes?","back":"Storing all the suffixes of X explicitly would take O(n^2) space. Even so, the suffix trie represents these strings implicitly in O(n) space.\n"},{"title":"card_1753","front":"What is the upper bound on character comparisons in Boyer-Moore?","back":"At most 3n character comparisons in the worst case, and this bound is tight.\n"},{"title":"card_1754","front":"What is a mixed graph?","back":"A graph that has both directed and undirected edges.\n"},{"title":"card_1755","front":"What is a strongly connected graph?","back":"A directed graph G is strongly connected if for any two vertices u and v of G, u reaches v and v reaches u.\n"},{"title":"card_1756","front":"What is an adjacency map?","back":"An adjacency map is very similar to an adjacency list, but the secondary container of all edges incident to a vertex is organized as a map, rather than as a list, with the adjacent vertex serving as a key. This allows for access to a specific edge (u, v) in O(1) expected time.\n"},{"title":"card_1757","front":"What can we claim of the performance of adjacency map?","back":"We find that it essentially achieves optimal running times for all methods, making it an excellent all-purpose choice as a graph representation.\n"},{"title":"card_1758","front":"What is the upper bound on the number of edges in a graph?","back":"n^2\n"},{"title":"card_1759","front":"How can an adjacency matrix be made space efficient?","back":"If edges do not have auxiliary data, a Boolean adjacency matrix can use one bit per edge slot, such that A[i, j] = True if and only if associated (u, v) is an edge.\n"},{"title":"card_1760","front":"What are some uses of DFS for testing of properties of graphs?","back":"- whether there is a path from one vertex to another (transitive closure)\n- whether or not a graph is connected\n"},{"title":"card_1761","front":"What is a tree edge and what is a non-tree edge in DFS?","back":"Whenever an edge e = (u,v) is used to discover a new vertex v during the DFS algorithm, that edge is known as a discovery edge or tree edge, as oriented from u to v. All other edges that are considered during the execution of DFS are known as non-tree edges, which take us to a previously visited vertex.\n"},{"title":"card_1762","front":"What is special about discovery edges in DFS?","back":"Since we only follow a discovery edge when we go to an unvisited vertex, we will never form a cycle with such edges. Therefore, the discovery edges form a connected subgraph without cycles, hence a tree. Moreover, this is a spanning tree because, as we have just seen, the depth-first search visits each vertex in the connected component of s.\n"},{"title":"card_1763","front":"What is the runtime of DFS starting at vertex s, where ns is the number of vertices reachable from s, and ms is the number of incident edges to those vertices?","back":"O(ns + ms)\n"},{"title":"card_1764","front":"What is the running time of BFS if ns is the number of vertices reachable from vertex s, and ms ≤ m is the number of incident edges to those vertices?","back":"Similar to the one of DFS, with the algorithm running in O(n + m) time, or more specifically, in O(ns + ms) time.\n"},{"title":"card_1765","front":"Under what circumstances does DFS do better than BFS in directed graphs?","back":"- finding a directed cycle in the graph\n- identifying the strongly connected components\n"},{"title":"card_1766","front":"What is the transitive closure of a directed graph?","back":"It's a directed graph where the vertices are the same as G, but vertices are connected directly when a path exists between those vertices in G.\n"},{"title":"card_1767","front":"What is the runtime of generating the transitive closure of a directed graph and what method can be used?","back":"Could use Floyd-Warshall, but it is O(n^3), and you may not need the minimum path weight.\nRepeated calls to DFS results in better asymptotic performance when the graph is sparse and represented using an adjacency list or adjacency map. In that case, a single DFS runs in O(n + m) time, and so the transitive closure can be computed in O(n^2 + nm) time, which is preferable to O(n^3).\n"},{"title":"card_1768","front":"What is the time and space complexity of topological sort?","back":"Let G be a directed graph with n vertices and m edges, using an adjacency list representation. The topological sorting algorithm runs in O(n + m) time using O(n) auxiliary space, and either computes a topological ordering of G or fails to include some vertices, which indicates that G has a directed cycle.\n"},{"title":"card_1769","front":"What is the running time for Dijkstra's algorithm?","back":"O((n + m)log n)\n"},{"title":"card_1770","front":"What is the running time of Kruskal's algorithm?","back":"O(m log n)\n\nFor a connected graph, m ≥ n − 1, and therefore, the bound of O(m log n) time for ordering the edges dominates the time for managing the clusters (which is log*n).\n"},{"title":"card_1771","front":"What is another name of the log-star function?","back":"The inverse of the tower-of-twos function.\n"},{"title":"card_1772","front":"What does log∗ n mean?","back":"log∗ n is the number of times that one can iteratively take the logarithm (base 2) of a number before getting a number smaller than 2.\n"},{"title":"card_1773","front":"What is internal fragmentation?","back":"Internal fragmentation occurs when a portion of an allocated memory block is unused.\n"},{"title":"card_1774","front":"What is the worst-fit algorithm?","back":"The worst-fit algorithm searches the free list to find the largest hole of available memory.\n"},{"title":"card_1775","front":"Why is the worst-fit algorithm the best for avoiding internal fragmentation?","back":"The worst-fit algorithm attempts to keep contiguous sections of free memory as large as possible.\n"},{"title":"card_1776","front":"How does in-place DFS work and how does it save precious space when performing garbage collection?","back":"The main idea for performing DFS in-place is to simulate the recursion stack using the edges of the graph (which in the case of garbage collection correspond to object references). When we traverse an edge from a visited vertex v to a new vertex w, we change the edge (v, w) stored in v's adjacency list to point back to v's parent in the DFS tree. When we return back to v (simulating the return from the \"recursive\" call at w), we can then switch the edge we modified to point back to w, assuming we have some way to identify which edge we need to change back.\n"},{"title":"card_1777","front":"What is internal memory?","back":"Main memory or core memory.\n"},{"title":"card_1778","front":"What is external memory?","back":"Usually consists of disks, CD drives, DVD drives, and/or tapes.\n"},{"title":"card_1779","front":"What is a common adage among computer architects?","back":"A program spends 90 percent of its time in 10 percent of its code.\n"},{"title":"card_1780","front":"What are the best to worst caching strategies?","back":"The LRU strategy has been shown to be usually superior to the FIFO strategy, which is usually better than the random strategy.\n"},{"title":"card_1781","front":"What is I/O complexity?","back":"Minimize the number of disk transfers needed to perform a query or update.\n"},{"title":"card_1782","front":"How many children does each node of a (2, 4) tree have?","back":"2-4\n"},{"title":"card_1783","front":"How many children does each node of a (a, b) tree have?","back":"a-b\n"},{"title":"card_1784","front":"What is an (a, b) tree?","back":"An (a, b) tree is a multiway search tree such that each node has between a and b children and stores between a − 1 and b − 1 entries. The algorithms for searching, inserting, and removing entries in an (a, b) tree are straightforward generalizations of the corresponding ones for (2, 4) trees.\n"},{"title":"card_1785","front":"What are the bounds on the height of an (a, b) tree storing n entries?","back":"The height of an (a,b) tree storing n entries is Ω(log n/log b) and O(log n/log a).\n"},{"title":"card_1786","front":"How do we select the a and b of an (a, b) tree?","back":"To minimize disk accesses, we select the parameters a and b so that each tree node occupies a single disk block (so that f (b) = 1 if we wish to simply count block transfers).\n"},{"title":"card_1787","front":"What is the main application of (a, b) trees?","back":"maps stored in external memory\n"},{"title":"card_1788","front":"What is a B-tree in relation to an (a, b) tree?","back":"A B-tree of order d is an (a, b) tree with a = ceiling(d/2)\u000e and b = d.\n\nWe specifically choose d = (M/B) − 1 so that we can afford to keep one block from each input sequence in main memory at any given time, and to have one additional block to use as a buffer for the merged sequence.\n"},{"title":"card_1789","front":"A B-tree with n entries has what I/O complexity and uses how many blocks?","back":"- O(log(base B) n) for search or update operation\n- uses O(n/B) blocks, where B is the size of a block\n"},{"title":"card_1790","front":"if main memory has size M and each block has size B how many blocks can we store within main memory at any given time?","back":"Up to M/B blocks.\n"},{"title":"card_1791","front":"What is the I/O complexity, given an array-based sequence S of n elements stored compactly in external memory, of sorting S?","back":"- O((n/B)log(n/B)/log(M/B)) block transfers where M is the size of the internal memory and B is the size of a block.\n- O(n log n) internal computations"}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment