CS 2110 Prelim 2

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

What are the two ways to deal with collisions in hash tables?

1. Chaining - creating a linked list of all the objects that were assigned to that index 2. Probing - looking for the next available slot and placing the object in that index Chaining is faster

What are the requirements of a binary search tree? What is a binary search tree?

1. Each child must have at most 1 parent 2. There cannot be a cycle between nodes A binary search tree is a list of parent and child nodes by which each parent has between 0 and 2 children. Because it is recursively defined (either 0 children, 1 child, or 2), each child is also a tree.

What are the three invariants of a binary search tree?

1. Each node contains a value 2. All values on the left of the subtree are less than the value in the current subtree 3. All values on the right of the subtree are greater than the value in the current subtree

What are the four types of sorting algorithms?

1. Insertion sort: going through each element in list and moving it back to its proper spot (anything less than that value is sorted, and anything greater is not sorted) 2. Selection sort: takes each element and scans the rest of the array to see where it should be placed 3. Merge sort: first, dividing up the array into as many little mini-arrays as possible, and sorting those recursively (takes lg(n) time). Then, merging all of the mini-arrays back together (O(n)). So, takes O(nlg(n)) time total. However, you need another array, so space complexity is O(n). 4. Quicksort: you choose a pivot and scan all the elements to the left and right of it: any element that is greater than the pivot and to the left will be moved to the right, and vise versa. You do a recursive call on the left and right sides of each. At the end you will have a sorted array. Time takes O(nlg(n)) in average case because you divide by (on average) 2 each time and scan the whole array so you multiply by n. In the worst case when it is already in its order, it takes O(n^2) times because for each pivot you scan through the whole array.

What is a separation of concers?

1. Model: gathering the pieces to make the GUI - the basic objects that will make it work 2. View: making the GUI look pretty 3. Controller: responding to events and updating the model.

What is the difference between a BST and a binary heap?

A BST is used to search the whole tree A binary heap is to just keep track of min/max value - it's less complex than BST and takes less time.

What is a balanced BST?

A balanced BST is when the left and right subtrees differ in height by no more than 1.

What's the difference between a checked exception and an unchecked exception?

A checked exception happens because the compiler helps ensure exceptions are handled. An unchecked exception is one in which the compiler doesn't check for (i.e. nullPointerException, ArithmeticException, and ArrayIndexOutOfBound exception)

What is a leaf?

A child of a BST with no children

What is an adjacency matrix?

A matrix that represents a graph in a 2D array - space is O(v^2), where v are the vertices. However, checking whether there's an edge between two vertices takes constant time, but finding all the incoming/outgoing edges takes time proportional to the number of vertices.

What is a monitor?

A monitor is an object that has all of its public methods synchronized

What does a mutex do?

A mutex uses the synchronization keyword in the method header, and it holds a lock on the object that's being modified so only one thread can access the object at once. Once the method finishes, the mutex is released

What is arrayIndexOutoffBounds?

A runtime exception

What is an adjacency list?

An array of linked lists that keeps track of the outgoing edges. Only require O(V+E) space. Finding outgoing edges is efficient, but not finding incoming edges.

How do hash tables work?

An object is assigned to a numerical value in a table based on its unique characteristics. We use the hashCode() function to generate a hash code, and then divide by mod the length of the table/array to assign it to a specific index.

How long does it take to access an element in a linked list versus an arrayList?

Arraylist - constant time. You can do this because you're getting a certain value - O(1) Linkedlist - there are no pointers from the start to every node, so it takes O(n) time.

What is the rule on subtyping with different objects? I.e. List vs ArrayList and List<Object> vs. List<String>

Arraylist is a subtype of list. List<String> is not a subtype of List<Object> - subtyping doesn't work this way, only for the variable type itself.

what are the benefits and drawbacks of a doubly linked list

Benefits: easier to find/seach/add Drawbacks: more memory and management

What is big O notation, and what does it calculate?

Big O is the upper bound during runtime of a code - it calculates the worst case scenario. Tightest upper bound refers to the closest function that is the upper bound of the current function.

What is the difference between iterable and iterator?

Both are interfaces: you first implement iterable into the class you want to be able to iterate over. Then, you make an iterator object using the iterator() method. In order to do this, though, you must define the iterator class. The iterator class has the hasNext() and next() methods (next() can throw NoSuchElementException if there is no next value(). Any class that implements iterator (or an array) can be used in a for each loop

What are Maybe and Optional used for?

Both are variables that can either contain a value, or can contain null. They both have methods isPresent() to check if there is a value and get() to retrieve the value. For get(), it should be called using a try-catch block because it can return NoMaybeValue if there is nothing there. get() will throw a checked exception for Maybe and an unchecked exception for Optional.

What's the difference between comparable and comparator?

Comparable is an interface that a class inherits, and it contains the compareTo() method that you can override and personalize. This is attached to a specific type because it is implemented in a class. Comparator is also an interface, but one that you implement in the main method where you describe the compare() method that takes in two arguments. This interface is used for Integer.sort(), Array.sort(), etc. to sort any object. You must implement compare() in order to describe how you want to compare two objects. It is not necessarily attached to a type.

What is comparator?

Comparator is another interface that is a general way for you to compare two objects of any type. It contains the compareTo method so you can compare any two objects.

What are the two types of graphs? What are out-degree and in-degree edges?

Directed: from vertex A to B In-degree edges: number of edges coming in Out-degree edges: number of edges going out Undirected: an edge between A and B Both edges and vertices can have labels that carry meaning

What is the difference between an error and an exception?

Error is an error in the program and is the programmer's fault, while exceptions can be caused by the programmer or the client (if the client makes a mistake)

What are the four steps in a loop invariant?

Establishment: does the loop start right Preservation: does what happens inside the body keep the invariant true? Postcondition: does the loop end properly? Termination: does each iteration of the loop make progress towards its termination?

What does finally do?

Finally executes regardless of which part of the try-catch statement occurs; it runs before the try-catch statement finishes.

How do you show that O of some function is really an upper bound?

Find the limit as n approaches infinity of the actual function/O(that function). If it approaches 0, then O of the function is an upper bound of the function. OR - Give a witness pair. That is, find a k>1 and an n0 such that when the O(function) reaches n0 at the k value specified, it will be the upper bound of the function as n approaches infinity.

How do you calculate O(n)?

Go through the code line by line and determine how long each fragment takes in the worst case scenario. Note: constants don't matter Conditional statements: constant time O(1) Assignment statements: constant time O(1) For statements (with constant upper bound): constant time and it depends on how many iterations For each loop: O(n) because you're iterating through the input. Nested for loops: multiply inner time complexity by outer time complexity While loops: if iterating through whole array - O(n) If dividing in half repeatedly - Log(n)

What is linear probing?

Going through the array one-by-one looking for an empty slot. If you reach the end of the array, you wrap around and start looking from index 0 of the array for that empty spot.

How to find the height and depth of a BST?

Height = number of edges from top to bottom most node Depth = number of nodes in height from top to bottom most (usually = height + 1 to account for top node).

What is a branching factor?

How many children each parent has (i.e. in BST, it is 2)

What is an IOException, and what is it a subclass of? What else is a subclass of this superclass?

IOException is a subclass of Exception - nullpointerexception is also another subclass. Botha are runtime exceptions.

How do we know if a path is a cycle?

If the first and last vertices are the same.

What are in-order, pre-order, and post-order BST traversals?

In-order: left, root, right (smallest to greatest) Pre-order: root, left, right (think pre is for root, so it comes before) Post-order: left, right, root (think post is for root, so it comes after)

What is the time complexity for the four different types of sorting algorithms?

Insertion Sort: Worst case: O(n^2) Best case: O(n) Selection Sort: Worst/Best Case: O(n^2) Merge sort: Best/Worst case: O(n*lg(n)) Quick sort: Avg. case: O(nlg(n)) Worst case: O(n^2)

What are the two stable sorting algorithms?

Insertion sort and merge sort

What is inversion of control, and why are GUI's involved?

Inversion of control refers to event-driven programs - the client's actions cause certain parts of the program to run. This happens in GUI because the client's actions dictates what gets executed

What is the event dispatch thread and what does it do?

It continually waits for events to happen. When they do, it makes a new Event object and calls it on the element that caused the event to happen to trigger a response.

What does actionListener do?

It is a class, and when you make an object, you add it to the source event and specify what you're listening for. You then use a lambda expression to signify what happens if that event gets executed.

What is the collections framework?

It is an interface that, when implemented, has built-in methods that can take in any type (Type 'T') and do something with it. For example, making a LList that implements Collections can be a list of Nodes that uses the methods in the Collections interface.

What is space complexity?

It refers to the amount of space needed to perform an algorithm I.e. binary search only takes up 1 array - so O(n) Merge sort makes mini arrays and then adds them up, so takes O(n) space.

What is the time complexity of searching through a hash table?

It's 1+ the load factor of the table, which is just constant time - O(n)

When can we used a lambda expression, and how does it work? Give an example with actionListener and button. Why can't we do it with MouseListener?

JButton a = new JButton(); a.addActionListener(e -> System.out.println("Button pressed");); the ActionListener interface only has one method, so we can abbreviate a class that implements the interface - e: denotes the argument/ActionListener event) After e ->: what happens in the function MouseListener has more than one method so it wouldn't be able to use a lambda expression. It would be as follows: JButton b = new JButton(); b.addMouseListener(new MouseExtend); And in a separate class: class MouseExtend extends MouseListener{ MouseExtend(){ System.out.println("Something happens"); } }

How do I make an application as a GUI?

JFrame - the pop-up window, frame you can use add() to add to it A JLabel will be a label that will pop up in the JFrame Example: JFrame a = new JFrame(); a.add(new JLabel("Hello"), BoarderLayout.NORTH); BoarderLayout is the standard way to put things in certain spots

What is the best object type for pushing and popping elements?

Linked list - less time and energy than a heap - stacks Heap is to maintain order - it's a priority queue

How can I instantiate an object with a generic type? (Example with LinkedLists)

LinkedList<String> a = new LinkedList<>(); CANNOT do: LinkedList<int> b = new LinkedList<>() because the generic type has to be an object.

What are some examples of objects in the collections framework?

List (ArrayList, LinkedList), and Sets (HashSets, LinkedHashSet)

What is a locking level?

Locking levels help avoid deadlock and create an algorithm for synchronization. The upper bound of a locking level on a public synchronized method is the method itself. If L1 is acquired before L2, then L1 < L2. When locks do not uphold this inequality, that's when deadlocks likely occur

What are the three different threads that run in a GUI, and what do each of them do?

Main thread - follows what the user does Application thread - continuously checks to see if events have been created (as a result of a client action) Rendering thread - continuously show the display

What is the difference between modular and multiplicative hashing

Modular hashing takes longer and is hashcode() % length. Multiplicative uses multiplication to generate a hash code and is faster

If I have an error thrown in a catch block, will it go to another catch block?

No, it will not because that part of the code is not in a try-catch block. If the catch statement is executed and finishes, whatever comes after it runs

What is the time complexity of searching a BST, and why?

O(lg(n)). This is because in the worst case where the value is at the bottom left, for example, it will take us log(base 2)(n) time to get there because each time, we're splitting the tree in half (as a result of the invariant)

What is the time complexity of binary search? Why?

O(lg(n)). This is because you're dividing the array into two as many times as possible, so in the worst case where the thing you're looking for is at the end, it would take log(base 2)(n) times to get there.

What is the time complexity to rehash all the elements in the table to a larger array?

O(n)

How much space does quicksort take and why?

Quick sort takes O(n) space (worst case) and the call stack executes O(log(n)) times on average because that's the number of calls it executes in the call stack.

What are race conditions?

Race conditions are when two different threads try to access and modify the same object at the same time. This can cause problems.

What's the difference between paint() and repaint()

Repaint() requests a repaint if something has chanced where the view should be different. Paint() gets called in repaint() and cannot be accessed directly. Other methods that can have paintComponent(), paintBoarder(), etc. - these paint certain parts of the GUI

What is the difference between <T> and <?> ?

T can be any type, but the client knows the type. With ?, the client does not know the type of the list, but can view elements in the list.

What is the load factor of a hash table?

The average number of objects per bucket in the table.

What is clustering?

The measurement of how random the hash code assigns keys to buckets

If class A extends B, then making instance c of type B call a method only in A, that then calls a method that is both in A and B - will the method in A or B execute?

The method in B

After how many tests can I be sure that there are no race conditions in an algorithm?

There are no number of tests that can prove that, because you could just be getting lucky each time. You need a formal proof to prove this.

What do cores do?

They are part of your computer, and they let jump back and forth between thousands of threads to let your computer process so many things at once (some cores can run multiple threads at once). However, the Operating system can interrupt the core at any time

What is a tail-recursive method?

This means that immediately after the recursive call happens, the method returns. You cannot do any operations on the recursive call, such as +1 or * another recursive call. The point is that you don't have to create a new call stack because all you have to 'remember' is the recursive method.

How to prove that something is big-O? (upper bound)

To show that f(x) is contained in O(g(x)), you want to find a k and an n such that f(x) < k*g(x) for all values above the n you choose.

What is topological sorting?

Topological sorting: sorting the graph so that the 0th degrees come first, then the 1st degrees, and so fort.

T/F I can concatenate strings with chars

True - you cannot cast a char to a string

What is variance?

Variance is the idea that you can have a subtype relationship between a generic type and a specified type. I.e. String < Object, but if you make an object of type Object and assign it to the String type object, it cannot add, say, an integer because now it's a String.

When do we use Exception e, and when do we just use Exception()?

When throwing an exception: throw new ArithmeticException(); When catching: catch(ArithmeticException e)

What is amortized cost analysis?

With rehashing all values, it takes O(n) time and is very expensive. However, it rarely happens, so on average, the cost of using add() gets down to O(1) (constant time) because you're geometrically increasing the size and rehashing barely happens. So, over time, the cost of adding becomes a lot lower.

If f(x) = 3x^2, is x^2 contained in this function?

Yes because a function contains itself

What are the benefits of using generics?

You have less duplicate code, therefore there are less mistakes to be made.

How to initialize an array?

char[] a = new char[]{'a', 'b'}; char[] b = new char[3]; b[0] = 'r'; b[1] = 'f'; ...

What does invokeLater() and Runnable do?

invokeLater() allows everything that's in the main method function to be executed on the swing event dispatch thread because it can't be used in main

How to make a new string based on a char array?

new String( - array - , - what index to start - , how many chars should be in string -);

What do wait() and notifyAll() do?

wait() blocks the current thread and releases the mutex so that other threads can access the object until the right conditions are met (i.e. wait() is not called anymore) notifyAll() unblocks all the threads waiting on this condition variable


Kaugnay na mga set ng pag-aaral

MGT 5000, Financial Management, Chapter 3

View Set

AP Psychology Chapter 6: Sensation & Perception

View Set

MUH3025 midterm prep (from quizzes)

View Set