CS Exam 2
How do you get a variable in a string
"yoyoyo, ${var}" uses double quotes
From char *s = (char *) malloc (sizeof(*s) * n), What does the char *s do? What does the sizeof operator do?
(char *s) Type cast: malloc only returns void * Cast tells compiler that program will use it as a char * sizeof(*s) sizeof operator: Takes a type or expression, evaluates to the number of bytes to store it
A BST is a valid AVL tree if the balance factor for every node is ________
-1, 0, or 1
When compiling assembly with C++, what flags do you use to compile the C++ code?
-Wall -m64 -Wall -g -c -o main.o main.cpp
What flags do you se to generate assembly from C++ code?
-m64, -mllvm -S
Does just one node have a height of 1 or 0?
0
Halt Opcode:
0
How do deconstructs work for derived classes?
1 - Derived class's destructor called 2 - Base class's destructor called OPPOSITE order of constructors
How would the virtual method tables work for something like this: Person *p = new Student();
1) Calls person constructor, makes virtual method table 2) Calls student constructor. Updates object. Updates VMT to be the student one
How to write a C++ program to execute IBCM code?
1) Create union called ibcm_instruction 2) define struct{} for each opcode 3) in another file check which struct the instruction aligns with and execute code
How does the delete min function work for a min heap?
1) Remove root (that is always the min!) 2) Put "last" leaf node at root 3) Find smallest child (else not a min-heap) 4) Swap node with smallest child if needed. 5) Repeat steps 3 & 4 until no swaps needed.
How to perform huffman encoding?
1) Store character frequencies in min-heap 2) Build huffman tree - take two characters that have lowest frequency - make them children of a new node - sum children frequencies as value for new node - add new node back into heap - repeat until you have 1 node, which is your min value as well as the huffman tree root 3) write prefix codes or tree to output file 4) re-read source file and for each character, output its prefix code
How do you attempt to reduce the number of access to slower levels of memory?
1) Temporal Locality Locality in time If an item is referenced, it will tend to be referenced again soon 2) Spatial Locality Locality in space If an item is referenced, items whose addresses are close by will tend to be referenced soon
What steps do you need to take in programming IBCM code?
1) Write high level pseudo code (C++) 2) Translate into IBCM instructions 3) Test by hand 4) Encode into machine code
3 important characteristics of huffman coding
1) building prefix codes from frequency of symbols in a string 2) more frequent characters represented with fewer bits 3) no prefix is a prefix of another code
If you assign a global vector x from a local vector y, how could you do this considering vector y will go out of scope?
1) deep copy 2) have x's array pointer point to y's array. it won't delete y's array when it goes out of scope
Name 3 new features of C++ 11
1) for each loops (ranged based for loops) 2) calling constructor in function argument with curly brackets 3) 'auto' keyword to infer function type
How to topologically sort a DAG?
1) have a counter and vector (queue) to store vertices (v) 2) add all v that have in-degree of 0 (no incoming edges) 3) until the queue is empty, a - get a vertex from queue b - set its num = counter. increment counter c - for each adjacent vertex w, subtract 1 rom its in-degree, and IF it equals zero after that, add that node to the queue 4) check if counter == number of vertices fin
A perfect hash function has what 2 things:
1) no blank spots 2) no collisions
Features of a directed acyclic graph (DAG):
1) no cycles 2) strongly connected - there is a path from every vertex to every other vertex 3) weakly connected - theres an undirected path from every vertex to every other vertex (can go both ways, direction not important)
How do you do pre-order traversal of a tree?
1, 2, 4, 5, 3
I/O Opcode:
1, next 2 bits specify I/O type
Our IBCM had a ____ bit accumulator
16 bit
IBCM Instruction format?
16 bits, All in hex first 4 bits are opcode (type of operation) Last 12 bits specify address for instruction and control instructions
One register in x86 can be multiple by ___ ____ or ____
2, 4, 8
Shift Opcode:
2, next 2 bits specify shift type, last 5 specify amount
At most, ___ register(s) and ___ 64-bit signed constant(s) can be added together to compute a memory address
2, one
In a perfect binary tree, number of nodes is
2^(h+1) -1
In a perfect binary tree, the number of leaves is
2^h
"Straight" encoding is ___ bits per char
4
How do you do in-order traversal of a tree?
4, 2, 5, 1, 3
How do you do post-order traversal of a tree?
4, 5, 2, 3, 1
ASCII has ___ bit(s) for encoding and ___ bit(s) for parity (error correction)
7, 1
ASCII is ___ bits per char
8
What is a proper binary tree?
A binary tree in which each node has exactly zero or two children.
What is a unique_ptr (C++11)
A pointer that ensures only one copy of an object exists
What is a weak_ptr (C++ 11)
A smart pointer that can tell whether an object still exists or has expired. Does not increment references for shared_ptr Useful if two objects point to each other and create a cycle.
What is a shared_ptr (C++11)
A smart pointer that counts the number of references and automatically deallocates local instances
What is a minimum spanning tree (MST)?
A spanning tree of a graph G is a subgraph of G that contains every vertex of G and is a tree But suppose edges have weights! "Cost" associated with the edge Miles for a transport link, for example Minimal-weight spanning tree: spanning tree with the minimal total weight
What happens on dynamic memory allocation
A subroutine is invoked (for either new or malloc()) The OS is consulted, if necessary, to allocate a page of memory This requires switching context back to the OS The heap directory is examined And new space is determined somehow The subroutine returns
What's the difference between AVL tree and BST?
AVL tree remains balanced after each operation.
When are pure virtual functions used?
Abstract classes where subclasses will define the functions
How do you represent a DAG?
Adjacency matrix
What are real world applications of TSP?
Any delivery system really because the cost is the amount of fuel you use
How is IBCM turing-complete?
Any program expressible in any programming language can be expressed in IBCM
Do linked lists or arrays have better spacial locality?
Arrays because they are represented in contiguous memory
How does Dijkstra's algorithm work?
Assume all nodes have distance and path values, a bool for 'visited', and edges with weights Vertex s = starting vertex 1) initialize each vertex's distance as infinity, add them to queue 2) set s.distance = 0 (this is where we're starting) 3) Repeat while the queue is not empty: a - assign vertex v = vertex with shortest distance *note* - the shortest distance can be found from the edge weight b - mark node as visited c- for each vertex w adjacent to v, if w is not known and v.distance + cost to travel to w is < w.distance (should be true since they're all initialized to infinity), w.distance = v.distance + cost of traveling there w.path = v At the end, you will have all your vertices with assigned distances and you can get the shortest path to any vertex by looking at the path values. Example: if node 7 has path value 4, which has path value 0, then the fastest path from 0 to 7 is 0 to 4 to 7
Difference between binary trees and binary search trees
BST's are sorted
CPU registers allow one access per ____ _____
CPU cycle
Memory hierarchy (fast to slow)
CPU registers --> caches --> memory --> disk
Why use priority queues?
CPU scheduling - operating system must choose which processes to run Management of limited resources - bandwidth on a router
What are splay trees good for?
Caches
How many bits are x86 registers?
Can be 16, 32, or 64 bits
If you insert a new node into a red-black tree where the parent and uncle are red, what do you do?
Change grandparent to red, parent and uncle to black. Changing grandparent might violate rules and make root red, so do it recursively, before rotations
How to pass a constructor as an argument for another class's method?
Curly brackets: TimeKeeper time_keeper {Timer()}; NOT TimeKeeper time_keeper (Timer());
In a callee function in x86, what do you need to do before anything else.
Decrement stack pointer sub rsp, 8
Restrictions on x86 add?
Destination cannot be a constant Memory cannot be accessed twice
Memory addressing restrictions of assembly?
Destination cannot be constant (mov 20, [rax]) You cannot access memory twice in one instruction (mov [rax], [var])
Ways to find the weighted shortest path of a graph?
Dijkstra's algorithm Greedy algorithm
Give an example of non-replicated (or non-repeated) inheritance
Don't think this occurs in C++ because it occurs in languages that do not allow shared or replicated inheritance
If you don't know how much space is required by your program, what type of memory allocation should you use?
Dynamic because memory can be put on the stack or heap (usually the heap)
Why does the stack pointer increment/decrement by 8 when you call push or pop?
Each pointer is 8 bytes
How do you calculate the height of a tree
Find the longest path from that node to a leaf
AVL Tree Runtimes: Find: Insert: Remove: Print:
Find: O(log n) Insert: O(log n) Remove: O(log n) Print: O(n)
How does the heap allocate memory?
Fixed-size-blocks allocation - A free list of available blocks is kept, and the appropriate number are allocated Buddy blocks - Blocks are divided into powers of 2, so the memory takes up the next highest power of 2 bytes
Binary Heap (implemented as min heap) ordering properties:
For every non-root node X, the key in the parent of X is less than (or equal to) the key in X. Thus, the tree is partially ordered.
What is the Traveling Salesperson Problem (TSP)?
Given a number of cities and the costs of traveling from any city to any other city, what is the least-cost round-trip route that visits each city exactly once and then returns to the starting city?
What is an MD5?
Given a string, generate a 128-bit hash
How to find the unweighted shortest path of a graph?
Given a vertex s, and assuming you have a queue and each vertex has a distance and path value, 1) add s to the queue 2) while queue is not empty: a - vector v = remove element from queue b - for each vector w adjacent to v, if w.distance == INFINITY, w.distance = v.distance + 1 (because its unweighted) w.path = v add w to the queue
What's a good example of using the 'auto' keyword with 'decltype'
Good for generic programming. template<typename T1, typename T2> auto sum(T1 & t1, T2 & t2) -> decltype(t1 + t2){ return t1 + t2; } int main(){ auto i = 1; auto j = 1.3; auto k = sum(a,b); cout << c << endl; }
Why do we care about shortest path on a graph?
Google maps can find the shortest route Internet traffic routing solve puzzles like Rubik's cube
Why use an AVL tree?
Guaranteed O(log n) running time on find, insert, and remove
How do we implement priority queues?
Have a vector<type> for storing heap values, and implement it as a binary heap
Basic idea of Kruskal's MST algorithm?
Idea: Grow a forest out of edges that do not create a cycle. Pick an edge with the smallest weight.
Why do you need to use trailing return type for an 'auto' defined function?
If you start manipulating the variables, the compiler won't know what type they are. Solution: decltype auto sum(T1 &t1, T2 &t2) -> decltype(t1+t2){} as you can see, the decltype tells the compiler to infer the type of t1 and t2
What methods are contained in a standard priority queue implementation?
Insert - inserts object with a priority assigned to it Find min - finds the minimum element Delete min - finds, returns, and removes minimum element
Runtime of binary heap operations?
Insert: O(log n) Delete min: O(log n) Find min: O(1)
What's missing from IBCM?
Integer multiply/divide Floating point support More than 1 user register Bigger address space
If rax is a register, what does [rax] do in x86?
It accesses the memory that the address stored in rax points to
What does add <reg>, <reg> do?
It adds the 2 values and stores it in the first one
What does the accumulator do in the IBCM?
It basically stores the current state based on the operations executed. So if you load 7 to the accumulator and subtract 4, the accumulator is 3.
What does this do? mov rsi, [rdx + rax + 16]
It finds the sum of rdx + rax + 16 and then it dereferences that value and moves it to rsi
Why does a hash function need to be deterministic?
It needs to return the same value each time for the same "thing"
What does the -f elf64 flag mean?
It tells the assembler the output format for the final executable - 64bit linux
How does IBCM's memory work?
It's an array of 4096 16-bit words These words store data and instructions
Problem with MD5
It's broken. Can generate two files with the same hash
When you call push in x86, what happens to the RSP (stack pointer)?
It's decremented by 8
When you call pop in x86, what happens to the RSP (stack pointer)?
It's incremented by 8
What are binary heaps used for?
It's one possible way to implement a priority queue
What is a parse tree used by/for?
It's used by a compiler to generate code, type check, and optimize code
What is a pure virtual function?
Its a function that has no body definition in the .cpp file EX: class shape { public: virtual void draw() = 0; }; any type of shape that inherits this class should define the draw method
From node x in a binary heap (implemented with array with x being the position in the array), how do you access the parent, right child and left child?
Left Child: 2 * x Right Child: (2 * x) + 1 Parent: x / 2 BUT the parent rounds down so if it's 5/2, then the parent is at 2 , not 3
While each list element has relationships with ____ elements, a tree element has relationships with ____ other elements.
List: 2 Tree : 3
Problem with dynamic dispatch?
Lots of runtime overhead: Program must maintain extra information Compiler must generate code to determine which member function to invoke
Memory in C: What are the qualities of the stack?
Managed by compiler automatically Lifetime is determined by program scope Cannot outlive procedure return Address space grows "down" from the top
Memory in C: What are the qualities of the heap?
Managed by programmer explicitly Lifetime is controlled by programmer Lives until freed by program Address space grows "up" from the bottom
What assembler do we use for our x86 labs?
NASM
When do the stack and heap meet in memory?
Never
Is a binary heap a complete binary tree ( a tree that's completely filled)
No, the bottom level is filled left to right and not always forms a complete tree
Runtime of prim's algorithm AND Kruskal's MST algorithm?
O (e log v) where e is the # of edges, v is the # of verticies
Heapsort runtime?
O(n log n)
TSP algorithm has what runtime?
O(n!) - very slow
Dijkstra's algorithm runtime:
O(n^2), where n is the number of vertices on the graph
Operator vs operand
Operator is + - / *, while operand is a number
Suppose you create a parentClass p and subclass s, how do you access p's methods from an s object in your main function?
Parent p; p.subclassFunction(); p.regularFunction();
Give an example of shared inheritance class student: public virtual person, public gp_list_node { ... }; class professor: public virtual person, public gp_list_node { ... }; class student_prof: public virtual professor, public virtual student { ... };
Person: Professor and student inherit from the SAME single copy of the grandparent (person)
Basic idea of prim's algorithm (spanning trees)?
Pick one node as the root, Incrementally add edges that connect a "new" vertex to the tree. Pick the edge (u,v) where: u is in the tree, v is not, AND where the edge weight is the smallest of all edges (where u is in the tree and v is not)
After calling a subroutine, what must one do with caller-saved registers?
Pop them off the stack
Three ways to traverse a tree
Pre-order, in-order, post-order
How to insert into a heap:
Put value at "next" leaf position Repeated exchange node with its parent if needed This is done by: 1) adding value to end of array/vector 2) percolate up through the tree and swapping the node with its parent until the node > parent OR if the position is at 1 (root)
The callee return value is saved to ____
RAX
Which register is used for the return value in x86?
RAX
Which register points to the top of the stack?
RSP
Which register should almost never be modified directly, as it points to the top of the stack?
RSP
Why is using a stack for calling convention implemented on most processors?
Recursion
What is RISC
Reduced instruction set computer Fewer and simpler instructions less chip complexity means they can run fast
When calling mov in x86, what can the destination and source be?
Register, constant, variable name, pointer[rbx]
After calling a function what might you need to do?
Remove parameters from stack Restore saved registers
How does a computer execute instructions? Think of program counter and instruction register
Repeats this process: Program counter is incremented by length of instruction Execute instruction from instruction register
Given the definition of malloc(): void *malloc (size_t size) What does it return? What is the parameter?
Returns an untyped pointer (can point to anything) Returns an address that is the location of at least size bytes of previously unused memory, and reserves that space. Returns NULL if there isn't enough space. parameter is the size in bytes
How to calculate bits used by huffman compression?
SUM of {prefix code length * frequency}
In a red-black tree, removal occurs how?
Same as a BST
Before calling a function, what things might you need to do?
Save registers that might be needed after the call Place parameters in registers/on stack Push extra parameters onto stack
Why are array implemented binary heaps better than pointer implemented ones?
Saves space Saves time (arrays work better with cache) Operations to find location in array are quicker Parent is easier to locate
What two ways can we resolve collisions in a hash table?
Separate chaining, open addressing
When inserting a node into the lowest node with an imbalance (x), what rotations do you perform if the insertion happens in the right subtree of the left child?
Single left rotation on the left child of x followed by a single right rotation on X
How is address space different in the stack and heap?
Stack: address space grows down from top Heap: address space grows up from bottom
What does lea do in x86?
Stands for load effective address It places the address of the second parameter into the first one. lea rax, [var] similar to int *rax = &var
Static vs Dynamic Dispatch
Static Decision on which member function to invoke made using compile-time type of an object Dynamic Decision on which member function to invoke made using run-time type of an object
How do you calculate the cost of a huffman tree?
The SUM of (frequency symbol occurs in string or file * path length from root to node) hint: you can get path length just by looking at the codes. If letter a occurs 3 times out of 7 total symbols, and has a code of 10, it will be (3/7 * 2) for THAT symbol only. add all of the symbols to get cost
Which constructor is called to initialize the data members inherited from the base class?
The base class's constructor is called first, then the derived class's constructor
What is serialization?
The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
What is in-degree in a topological sort?
The number of incoming edges to a vertex
In allocating static memory, what must be known?
The space required must be known at COMPILE TIME
How does TSP relate to hamiltonian path?
The traveling salesperson problem is thus to find the least weight Hamiltonian path in a connected, weighted graph
What's the difference between how IBCM and x86 execute code?
There is no difference. Both use a program counter and instruction register
What do and, or, and xor do in x86?
They perform the bitwise operations (on each bit)
What is memory access time (latency)?
Time it takes to access memory (duh)
Runtime of realloc()
Time to reserve new space: Θ(1) Time to copy old data into new space: Θ(n) where n is the size of the old data
What is memory cycle time
Time to write something into memory
Why use "auto" keyword on functions?
To let the compiler infer the type at runtime. Good for generic programming
How can you optimize dijkstra's algorithm?
Use adjacency lists and heaps Assume graph is connected
How to compare 2 values in x86?
Use cmp <var> <var>
How to append 2 c-style strings?
Use strcat(char *s1, const char * s2) returns s-style string with s2 appended to s1
How to copy 2 c-style strings?
Use strcpy(char *s1, const char *s2) returns c-style string
What exactly is a memory leak and what are the consequences of one?
When a program fails to release memory when no longer needed. Consequences: 1) reduces amount of available memory 2) in virtual memory, when the RAM has run out, it will use increasing amounts of hard disk
What is a "simple path" along a graph?
When all vertices along the path are unique
What are virtual method tables in dynamic dispatch?
When objects are created they contain a pointer to the virtual method table That table has the addresses of the methods For virtual methods, it follows the pointer to the object then follows that objects virtual method table pointer to lookup the method pointer
When are hash tables not ideal?
When you need to remove a lot of elements.
Why is buffer overflow bad?
You can overwrite the return address and set it to your own code
How do you code an array and sum its elements in IBCM?
You need the address of the array then loop through each element. To sum them up, you need an "adit" value saved of 5000. Then you can load that value, add the address of the element, store it in doit (doit is stored right after loading the sum), then load the sum and call doit (next line)
How do you pop the callee-saved registers?
You pop them in reverse order they were pushed
What is a hamiltonian cycle?
a Hamiltonian path that ends where it started
What is a hamiltonian path?
a path in a connected graph that visits each vertex exactly once
A C-style string is just
a pointer to a char
When a sub-routine is called, a number of things are pushed onto the stack. This is called _____ ______
activation record
Since you subtract 8 from the stack pointer at the start of a subroutine, what do you need to do at the end?
add rsp, 8
A hash table uses a fixed size ____ to store data
array
What do you have to assume in finding the weighted shortest path of a graph?
assume no negative weight edges
A binary search tree is a tree where all nodes have ...
at MOST 2 children
The hap starts at the ____ of memory
beginning
In memory caches, higher levels are ____ and _____
bigger, slower
Last byte in c-style string is ... last character in c-style string is...
binary zero \0
The instruction register stores what
bits which encode instructions
If you insert a new node that is the root node of a red-black tree, it must be painted _____
black
IBCM cannot have ___ _____
blank lines
How do you decode huffman code?
build tree from prefix codes - if there's no symbol mapped to a particular node, then leave its value blank for each symbol, start at root of tree and loop until you find the code. left is one, right is zero
What do cache hit and cache miss mean?
cache hit: address requested is in cycle cache miss: address requested is NOT in cycle
The function which is called by another function is called the _____
callee
The function which calls another function is called the _____
caller
What does realloc() do? void *realloc(void *ptr, size_t size);
changes the size of the memory object pointed to by ptr to the size specified by size Risky though because it changes the address of the pointer. If something else is pointing to the object they'll be pointing to invalid memory
A leaf is a node with no ______
children
If you inherit from two classes that have the same field name or method name, how can you overcome which one to choose?
chosenParentClass::method() chosenParentClass::field
When compiling assembly with C++, how do you link the C++ and assembly?
clang++ -m64 -Wall -g assembly.o main.o
How to indicate multiple inheritance C++?
class subClass : public parent1, public parent 2 { }
How do you indicate a class inherits another in C++?
class subClass : public parentClass
What is CISC
complex instruction set comptuer more complex instructions more chip complexity means harder to run fast
The unique_ptr<> does not support ____, but you can move it from one unique_ptr<> to _____
copying, another unique_ptr<>
AVL tree and splay tree have the same _______ time to inset a series of elements
cumulative
What is an auto_ptr (C++11)
currently deprecated stores a pointer a single allocated object and ensures that it the object is deleted when it goes out of scope
Program speed is affected by where the ____ is
data
In a perfect binary tree, all leaves have the same ___
depth
In the C calling convention, the stack grows ______, toward the lower memory addresses
down
In a BST, we assume _____ are not allowed
duplicate values
How to declare a variable in IBCM?
dw (declare word)
How to print in bash?
echo 'Yo'
The stack starts at the ____ of memory and grows _____
end, backward
How does percolate down work when removing from a min-heap?
first, call percolateDown(1) as you are starting at the root. The remove min method should place the last node as the root 1) store value at root while there is a left child{ check if right child. assign that to 'child' is right child less than left child? if so, make . child the right child if child is less than parent, assign child to parent } finally, you have found the correct 'hole' or position to put the root. heap[hole] = value stored at root
Storage allocated by malloc is reserved _______ , and you can give it back by passing it to _____
forever, free() void free(void *ptr);
Huffman trees are always ____ binary trees
full
For TSP, we assume the graph is
fully connected
Give an example of replicated (or repeated) inheritance class student: public virtual person, public gp_list_node { ... }; class professor: public virtual person, public gp_list_node { ... }; class student_prof: public virtual professor, public virtual student { ... };
gp_list_node: Professor and Student inherit from separate copies of the grandparent (person)
For priority queues, the size of heap is always one less than the number of elements in the vector because...
having a value stored in the zero index would be problematic for accessing nodes
Dynamic memory is stored on the ____
heap
Pointers and objects created by the programmer are managed by the ____
heap
How to multiply a variable in x86?
imul <reg64>, <reg64>
How to increment a variable in x86?
inc <reg>
Runtime for priority queue operations?
insert - O(log n) find min - O(1) delete min - O(1)
for each loop in c++?
int my_array[5] = {1, 2, 3, 4, 5}; for (int &x : my_array) { x *= 2; }
Do we use intel syntax or AT&T syntax for our assembly?
intel
If you make a class that has all pure virtual methods, then
it effectively acts like a Java interface
SHA (secure hash algorithm) is more secure than MD5 because
it generates a hash value up to 512 bits
What happens to a shared_ptr when nothing points to it anymore?
it is automatically deallocated by the compiler
What is lossy compression and what are some examples?
it's when some data is lost, but not "noticeable" data Examples: mp3 jpeg mpeg (video version of jpeg) typical compression ratio is 10:1
Hash tables store _____
key value pairs
Assembler translates assembly to _____ _____ which are instructions represented as patterns of _____
machine language, bits
How does the mov command work in x86?
mov <destination>, <source>
For n-node BST, worst case is ____
n-1
When compiling assembly with C++, what do you type to compile the assembly?
nasm -f elf64 -g -o assembly.o assembly.s
How to negate a number in assembly?
neg <value>
Dijkstra's algorithm does not work for ...
negative cost edges
When you use call in x86, it pushes the address of the ____ instruction onto the ____, then _____ to the label
next, stack, jumps
Can you create instances of an abstract class?
no
Does a subclass HAVE to define the method body for a pure virtual method
no BUT it does if it wants to be able to be instantiated, as a class can only be instantiated into an object if ALL the methods have defined bodies
What is lossless compression and what are some examples?
no data is lost in compression examples: morse code PNG images run-length encoding typical compression ratio is 4:1
TSP is NP-complete, meaning....
no known efficient solution runs at O(n!) - very slow
When do memory leaks occur?
no reference to allocated storage so whatever object you're trying to access can never be reached lose reference to variable because it goes out of scope or is reassigned
C++11 makes it easier to check for a NULL pointer how?
nullptr
Load factor of a hash table =
number of elements / size of table
When creating a subclass object, the constructor of each subclass does what to the virtual method tables?
overwrites the appropriate pointers in the virtual method table with the overridden method pointers
how to access inherited methods from a subclass?
parentClass:: function();
After the subroutine function body, what do you need to do to the callee-saved registers?
pop them from the stack
When you use ret in x86, it ____ the return address from the stack, then _________
pops, jumps
Suppose you are passing three parameters to a subroutine, but you have something store in rdi, what do you do?
push rdi mov rdi, var1 mov rsi, var2 mov rdx, var3 call function pop rdi
What do you need to do if you use the callee-save registers in a subroutine?
push them onto stack
If the caller wants to save r10 and r11, what must they do?
push them onto the stack
Which two registers may be modified by the callee
r10, r11
What are the callee-save registers?
rbx, rbp, r12-r15
Which registers may NOT be modified by a subroutine callee?
rbx, rbp, r12-r15
Which six registers are used for parameter passing?
rdi, rsi, rdx, rcx, r8, r9
When inserting into a red-black tree, what color does the node have by default?
red
How to go from connected graph to spanning tree?
remove an edge so it's no longer connected
What does int strlen(char *s) do?
returns the number of chars in s
If you need to pass more than 6 parameters to a subroutine in x86, what order do you push them in?
reverse order
Depth of a node is the length of the path from the _____ to the node
root
How to adjust dijkstra's algorithm to find the shortest path to a single destination?
same algorithm, but stop when you find the distance value for the destination node
Binary heap operations:
same as priority queue
Three types of shortest path algorithms for graphs:
single pair - find shortest weighted path from a vertex v to every other vertex w single source all pairs traveling salesman is a variant
Differences using C++ to compile assembly?
source/destination order is reversed in instructions add q after instructions dollar sign before constants register names begin with %
Function calls and returns are managed by the ____
stack
Registers are saved on the ____
stack
Static memory is stored on the _____
stack
The activation records are kept on the _____
stack
alloca() allocates memory on the ____ while malloc() and new allocated memory on the ____
stack, heap
How to use C++11 features with gdb?
std=c++11
The program counter stores what
the address of an instruction
For separate chaining, the load factor is ...
the average number of elements in each linked list
The stack and heap do what as the program progresses
the both grow toward the middle of the memory
If a class contains at least 1 abstract method, then
the entire class is abstract
cache page size is...
the number of contiguous bytes that are moved into the cache at one time
What is a processor cycle?
the time it takes to execute a "simple" instruction - like add tax, ebx
Why don't hash tables have findMin or findMax?
they don't have an ordering property
When you add to the rsp, you are going up/down the stack?
up
Once you compare values in x86, how do you evaluate them?
use je <label>, jg<label>, jl <label> equal, greater than, less than --> jump to label
How to indicate a method uses dynamic dispatch?
use virtual keyword
How do you specify shared inheritance?
use virtual keyword class professor: public virtual person{}
How to declare a variable in bash?
variable=echo
What is a buffer overflow attack?
when you read in a string that goes beyond the size of the buffer
Applications of minimum spanning trees?
wiring a house cable TV lines power grids internet connections
All leaves have a height of _____
zero
Before C++11, NULL for pointers was actually ____ which made it hard because you are type checking a pointer against an _____
zero, int
For every node in an AVL tree, the height of left and right sub-trees differs by at most ____
1
For separate chaining, the average time on a successful find is
1 + (load factor / 2)
Why use a red-black tree vs an AVL tree?
AVL trees require more rotations. It can be a persistent data structure - retains a "memory" of its mutations
How does linear probing work?
If hash(k) results in a collision, it finds next available spot ... hash(k) + 1, hash(k) + 2, etc
How does double hashing work?
If hash(k) results in a collision, it finds next available spot by adding (i * hash2(k)) So first will look at hash(k) + (1 * hash2(k)), then hash(k) + (2 * hash2(k)), etc
How does quadratic probing work?
If hash(k) results in a collision, it finds next available spot by adding i^2 to hash(k). So first will look at hash(k) + 1, then hash(k) + 4, hash(k) + 9, etc.
With an AVL insert, what 2 cases do you perform a single rotation?
If the insert occurs in the left subtree of the left child of X OR in the right subtree of the right child of x X is the lowest node where there is an imbalance
With an AVL insert, what 2 cases do you perform a double rotation?
If the insert occurs in the right subtree of the left child of x OR in the left subtree of the right child of x X is the lowest node where there is an imbalance
Problem with perfect binary trees?
It can only hold n values where n = 2^(h+1) -1. Cannot have 5 values for example
How does a hash function work?
It takes in a "thing" and returns an unsigned integer (can't be negative), which is modded by the array size
Why does the table size of a hash table need to be a prime number?
It will prevent thrashing Better distribution of hash keys (less clustering)
What is separate chaining (hash table)?
It's using some data structure to hold keys that are mapped to the same index in an array - linked list
What problems does linear probing have?
Large blocks of unoccupied cells, lots of attempts to solve collision as table fills (slower lookup times), holes when elements are removed
To resolve collisions using open addressing, what three methods can you use?
Linear, quadratic, double hashing
After performing insert/delete on an AVL tree, how do you update the balance factors?
Move back up to the root and update the balance factors
If you insert a new node into a red-black tree, where its parent is black, what do you do?
Nothing. None of the rules are violated
A splay tree is _____ amortized time (average time of all calls)
O (log n)
Separate chaining insert performance is
O(1) - assuming linked lists are unsorted
How long does a splay take? (Performance)
O(h), where h is the height of the tree
An AVL tree will take ____ time for each and every operation
O(log n)
A splay tree can look like a linked list so the running time can be ____ for a given operation - not same as amortized time
O(n)
If you sorted the linked lists in separate chaining, insertion has a performance
O(n)
Worst case performance using separate chaining
O(n)
Vector's insert is ____ worst case and _____ amortized when executing many operations
O(n), O(1)
In a red-black tree, when you insert a node where the parent is red, uncle is black and the node is the right child of the parent, what do you do?
Perform a left rotation on the parent and node. Now the node is the left child of the parent. Then you perform a right rotation on the parent and grandparent
In a red-black tree, when you insert a node where the parent is red, uncle is black and node is the left child of the parent, what do you do?
Perform a right rotation on the parent and grandparent. Recolor
Two ways to remove an element in a hash table
Rehash elements after deleting (very expensive) OR Put a placeholder value (also not ideal because table gets filled with them fast)
When inserting a node into the lowest node with an imbalance (x), what rotations do you perform if the insertion happens in the left subtree of the right child?
Single right rotation on the right child of x followed by a single left rotation on x
In a splay tree, anytime you insert/find/delete a node, you do what?
Splay the tree - perform tree rotations to make the node the new root node
The balance factor in an AVL tree measures what?
The height of right subtree - height left subtree
What do we call the sum of the depths of all the nodes in a tree?
The internal path length
How does the BST remove method work?
There are 3 cases for the node: 1) no children - remove node, adjust parent pointer to NULL 1) one child - adjust parent to point at the child, remove node 2) two children - call findMin() on the right sub-tree to find replacement and remove the element
How do splay trees improve performance in some cases?
They keep recently used nodes closed to the top (great for caches)
What are expression trees used for?
They're a way to keep an internal representation of a mathematical equation
How do you evaluate expression trees?
Traverse tree If operand, push onto stack If operator, pop two values from stack, evaluate, push result onto stack
What are splay trees bad for?
Uniform access - treating all data elements equally in terms of accessing them
When is an AVL tree balanced?
When balance factor = 0
When would you not want to use trees?
When items aren't sorted When we want less complexity (stack, queue) When we want an O(1) operation on retrieves - like a vector When we want O(1) time for all operations - hash tables pretty much achieve this
When do you do a tree rotation in an AVL tree?
When the balance factors are 2 or -2
With an AVL insert, when do you perform a single right rotation?
When the inserted node is in the left subtree of the left child of the lowest unbalanced node
With an AVL insert, when do you perform a single left rotation?
When the inserted node is in the right subtree of the right child of the lowest unbalanced node
When and how to you rehash a hash table?
When: Table gets too full How: Create bigger table and rehash all items from original table into the new one
In a red-black tree, children of every red node are ___
black
Red-Black tree root is always
black
In a red-black tree, every simple path from a node to any descendant leaf contains the same number of _______
black nodes (ether count NULL as black or don't. Just be consistent)
Length of a tree path is the number of _____ in the path
edges
What should be the size of a hash table array?
it should be larger than the number of elements and is usually a prime number
In a BST, every node in the left subtree has a key whose value is _____ than the root's key value, and every node in the right subtree has a key whose value is _____ than the root's key value
less, greater
In a hash table using separate chaining, the finds and deletes occurs in ____ time
linear - O(n)
When you decrease the load factor, you increase the amount of _____ used, but have fewer ____
memory, collisions
2 nodes are siblings if they have the same ______
parent
A root is a node with no _____
parent
Parse trees can be used to detect _____ in a person's code
plagiarism - it compares the structure of two programs while ignoring function/method order, variable names, comments
In a tree, there can be only one ____
root
For separate chaining, the average time on an unsuccessful find is
the load factor
Keys and value in a hash table do not need to be ...
the same type. They can be totally different
Hash functions should always return an _____ int.
unsigned. Cannot be negative