Non-Linear Data Structures Flashcards

1
Q

What is Big O notation?

A

Big O is a mathematical notation

Time/space complexity

that describes the limiting behavior of a function where the argument tends toward a particular value or infinity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When do we use Big O notation?

A

To determine the scale-ability of an algorithm as input grows large.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does Big O describe?

A

The performance on an algorithm

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does Big O have to do with data structures?

A

Certain operations can be more or less costly depending on what data structure is used (Array, Linked List, Queue, etc)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Name the different time complexities.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is exponential time complexity?

A

The opposite of logarithmic time complexity.

The exponential curve grows faster as the input grows.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which is time complexity more efficient?

log(n)

O(n)

A

While O(n) grows linearly with greater input,

O(log n) slows down at some point.

This makes O(log n) quadratic time more efficient that O(n) linear time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

At what point does the logarithmic algorithm slow down?

A

at some point, O(log n) will slow down.

When we reduce our work in half every step.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the Big-O for linear search vs. binary search?

A

linear search = O(n).

Iterate an array.

binary search = O(log n).

search a binary tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the five most common time complexity curves?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are non-linear data structures?

A
  1. Binary Trees
  2. AVL Trees
  3. Heaps
  4. Tries
  5. Graphs
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

When would we have a quadratic Big-O value?

A

When we use nested loops that each performs an iteration over the entire set of values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is logarithmic time complexity?

A

When we throw out half our items and narrow our search.

o(log n) - binary search tree lookup

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a tree?

A

A nonlinear data structure

stores elements in a hierarchy.

The “elements” are referred to as “nodes.”

Each “node” has data or values (could store objects).

The “lines” that connect “nodes” are called “edges.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are real-world applications of trees?

A

Tons of applications

databases

graphical user interfaces

websites

  1. Hierarchical data (files, folders) - File systems on your computer
  2. Databases (indexing) - use trees for indexing for fast database lookup.
  3. Autocompletion (matching previous queries) - Storing old search queries in a tree than trying to match old search queries to new entries.
  4. Compilers (translate code into new languages)
  5. Compression algorithms (JEPG, MP3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is special about a binary tree?

A

Allows for logarithmic time complexity

left subtree is smaller than root

right subtree is greater than root

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the top node of a tree called?

A

The top node is a tree is called “the root.

The root node has two children in a binary tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are the children nodes called in a tree?

A

The children nodes of a root node are called “leaves.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the run time complexity of various operations on binary trees?

A

Logarithmic time complexity

Lookup ( ) : O(log n)

addItem ( ) : O (log n)

deleteItem ( ): O (log n)

**if a tree isn’t set up properly the performance may degrade to O(n).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What values are we going to use for our binary search tree algorithm implementation?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do we implement the Node { } class in our binary tree?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do we implement the addItem( ) method in our binary search tree?

A

O ( log n ) operation!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do we implement the lookup( ) method in our binary tree?

A

O(log n) time complexity

Traversal:

Root, leftChild, rightChild

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do we implement a recursive method for printing nodes in traversePreOrder ( )?

A

Kick off recursion with method overloading

End with base condition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How do we implement a recursive method for printing nodes in traversePostOrder ( )?

A

Kick off recursion with method overloading

End with base condition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How do we implement a recursive method for printing nodes in traverseInOrder ( )?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

BT How do we implement traverseLevelOrder ( ) in our binary tree class?

A

O ( n ) operation!

Have to traverse every node in the tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

BT How do we implement min ( ) in our non-binary tree?

A

O(n) operation!

Have to traverse all values in tree!

Post order traversal.

We start with the leaves.

We find the min value in the left and right subtrees.

compare with root

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How do we implement min ( ) in our binary-search tree?

A

O(log n) operation!

We are only trying to find the left most leaf.

In every cycle, we are throwing out half of the nodes in the tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How do we implement equal ( ) method?

A

Pre-order traversal

root, leftChild, rightChild

First, compare the root nodes to check if equal.

Then, use recursion to look at their children nodes and compare if equal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What are two properties of tree nodes?

A

Depth and height

Depth = start at root, move down

Height = start at leaf, move up

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

How do we calculate depth (distance) in our tree?

A

Counting number of edges from root to node (target)

Height of root is zero

Ex. 8 has a depth of 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is recursion?

A

implementing repetition

when a function calls the method itself

we have a cycle

Terminating recursion:

We will call this method forever!

need a base condition to terminate

Java Implementation:

Java uses a stack for recursion (storing values)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How is recursion executed?

A

During each recursive method call

return value is stored in a stack

base condition is reached

result of last recursive method is returned to the previous method calls

This continues using the stack

until finally, results of expressions will return from first method call

**Java knows how to get back to previous step using a stack!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How do we calculate height?

A

​longest path from leaf to target node

Height of leaf node is zero

Ex. 20 (root) height is 3

Formula (height of tree)?

1 + max ( height(L), height(R) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How do we implement the height ( ) method in our binary tree?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is breadth-first tree traversal?

A

aka level order traversal

visit all nodes in the level before visiting the child nodes below the level.

Traversing level by level.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is depth-first traversal?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is pre-order traversal?

A

root, left subtree, right subtree

Start at root, go deep to all children and grandchildren

depth traversal!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is in-order depth traversal?

A

depth first traversal

start deep at left leaf node, root, right node

values come out in ascending order

reverse for descending order

rightChild, root, leftChild

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What is post-order traversal?

A

depth first traversal

leaves to root

start with left node, right node, branch root

Used in sorting data, heap properties, and mapping data connections.

Why?

start at the leaf nodes to calculate distances (height, depth) before moving to root nodes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What powers non-linear traversal?

A

Recursion

calling a function again

used for tree traversal algorithms like HeapSort and BubbleUp.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

How does the binary search algorithm work?

A

It begins in the middle of the data set.

In every set, it narrows the search by half.

with a million data values, we can find our value in only 19 comparisons.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

How do we implement a method equal ( ) to validate if two trees are equal?

A

Popular interview question!

Write a method equal ( ) to validate if two trees are equal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

How can we implement isBinarySearchTree ( ) ?

A

Popular Interview Question:

Write code to validate this binary tree

(Is this tree a binary search tree?)

Hint:

Pre-order traversal

check if each node is in the right range (vs. comparing to other nodes)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

How do we implement getNodesAtDistance ( ) in our binary search tree?

A

Popular Interview Questions:

Write code to print all nodes at distance k from root.

Hint:

use recursion

Think of breaking the problem down into smaller parts.

Decriment the distance as we traverse nodes

eventually distance reaches zero, print nodes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Implement size ( ) method to calculate the size of a binary tree.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

Implement max ( ) to return the maximum value in a binary tree using recursion.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

If our binary search tree is not structured properly what does our Big-O drop to?

A

O(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Implement countLeaves ( ) to count number of leaves in a binary tree.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

implement contains ( ) to check for the existence of a value in a binary tree using recursion.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

Implement areSibling ( ) to check to see if two values are siblings in a binary tree.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Implement getAncestors ( ) to return the ancestors of a value in a List

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

Implement isBalanced ( ) method to check if a binary tree is balanced.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

Implement isPerfect ( ) method to check if a binary tree is a perfect binary tree.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What are AVL trees?

A

Special types of binary trees that self balance themselves.

They do this by ensuring the right and left subtree difference isn’t greater than one on each insertion.

The difference in height between left and right sub trees still equals zero or less than one.

It it’s greater than one, they self-balance using rotations!

rotations come up in interviews.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

How do AVL trees work?

A

If difference between left and right tree is more than one, self balance using rotations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

What does a perfect tree look like?

A

Every level is full with nodes

Reality?

As we add and subtract values some branches get longer or shorter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

What happens to binary trees in reality?

A

They become unbalanced!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What is an unbalanced binary tree?

A

The right subtree is taller than the left subtree by more than one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

How do our search trees become unbalanced?

A

Insert sorted values in ascending or descending order!

Right skewed tree.

Sorted in descending order is a left tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

What is a right skewed binary tree?

A

Most nodes have only right children

Like linked-lists

if lookup (value) is in last node, O(n) operation!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What is a left skewed tree?

A

Worst type of binary tree.

Most nodes have only left children

Like linked-lists

if lookup (value) is in last node, O(n) operation!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What problem do AVL trees solve?

A

The Big-O of a binary search tree dropping from O(log n) to O(n) due to improper structuring.

How?

Only a balanced tree performs at logarithmic time complexity.

We cannot have a long branch.

Right, left skewed trees are like linked lists lookup (value) = O(n) operation.

How?

Self-balancing mechanism

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

What is an AVL interview question?

A

Add integers in a binary tree

show where imbalanced

show how to rotate (draw on whiteboard)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What are the four types of rotations?

A

The type of rotation depends on what side of the tree is heavy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

When do we perform a left rotation?

A

When the tree is heavy on the right

How?

height of left increases by one (becomes left child)

height of right decreases by one

Calculation:

balanceFactor = height (L) - height (R)

balanceFactor > 1 | left heavy (right rotate)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

When do we perform a right rotation?

A

When tree is heavy on the left side

height of right increases by one (becomes right child)

height of left decreases by one

Calculation:

balanceFactor = height (L) - height (R)

balanceFactor < -1 | right heavy (left rotate)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

AVL When do we perform a left-right rotation?

A

imbalance in left-child (left rotation) right-subtree (right rotation)

70
Q

AVL When do we perform a right-left rotation?

A

When imbalance in right-child (right rotation) left-subtree (left rotation)

71
Q

Set: 1, 2, 3, 4, 5

Add the set of numbers to an AVL tree.

  1. Start with an empty tree.
  2. Draw the tree at each step.
  3. Show the type of rotations required to rebalance the tree.
A
72
Q

Set: 5, 10, 3, 12, 15, 14

Add the set of numbers to an AVL tree.

  1. Start with an empty tree.
  2. Draw the tree at each step.
  3. Show the type of rotations required to rebalance the tree.
A
73
Q

What is the solution part one?

Set: 12, 3, 9, 4, 6, 2

Add the set of numbers to an AVL tree.

  1. Start with an empty tree.
  2. Draw the tree at each step.
  3. Show the type of rotations required to rebalance the tree.
A
74
Q

What is the solution part two?

Set: 12, 3, 9, 4, 6, 2

Add the set of numbers to an AVL tree.

  1. Start with an empty tree.
  2. Draw the tree at each step.
  3. Show the type of rotations required to rebalance the tree.
A
75
Q

What is a good resource for visualizing trees?

A

https://www.cs.usfca.edu/~galles/visualization/AVLtree.html

76
Q

How do we implement the insert ( ) method using recursion in our AVL tree?

A

A public method to kick off recursion.

  • In public method call the method and give it root, value
  • set root to object that is returned from private AVLNode

A private method to run recursion.

  • one scenario is when tree is empty! Return AVL node and set to root in public method
  • not empty, go right or left depending on value
77
Q

AVL How can we re-write this helper method using the ternary operator?

A
78
Q

How can we refactor the isBalanced ( ) method in our AVL tree?

A

Private helper methods:

isLeftHeavy ( )

isRightHeavy ( )

balanceFactor ( )

79
Q

AVL How do we refactor the balance ( ) method?

A

extract into a private helper method

80
Q

What is pseudo-code for detecting what kind of rotation is needed on a right heavy tree?

A
81
Q

How do we implement rotateRight ( ) and rotateLeft ( ) methods?

A
82
Q

How do we refactor the balance ( ) method to implement rotations?

A
83
Q

AVL how can we refactor setHeight ( ) method?

A

Extract logic into a separate private helper method

84
Q

How do we refactor the insert ( ) method in our AVL class?

A

extract logic into private methods:

setHeight ( )

balance ( )

85
Q

What is a heap?

A

A complete binary tree that satisfies the heap property

  1. Complete binary tree - all levels are full, nodes inserted from left to right

2. Heap property - value of every node is greater than or equal to children

86
Q

What is a complete tree?

A

Yes.

Every level is completely filled with nodes

Last level could have a hole

Levels filled left to right

87
Q

Is this a complete tree?

A

No.

Nodes are filled left to right

Missing a left node in last level

88
Q

What are the applications of heaps?

A

Many applications like in sorting and graph algorithms.

  1. Sorting data (HeapSort)
  2. Graph Algorithms (the shortest path between two nodes) - powers GPS
  3. Priority Queues
  4. Finding Kth smallest/largest value - popular interview question
89
Q

Is this tree complete?

A

No.

Second level is missing a node!

90
Q

What is a binary max heap?

A

Root node holds largest value

Children are less

largest value bubbles up to root

91
Q

What is a min heap?

A

Root holds smallest value

Children are all larger

smallest values bubble up to root nodes

92
Q

What are the heap operations and run time complexities?

A

remove ( ) - O (log n)

removing largest value in a heap

where log n = height of tree

insert ( ) - O (log n)

insert in leaf node, bubble up is log n operation.

max ( ) - O(1)

return root in max heap

min ( ) - O(1)

return root in min heap

Bubble ( ) - O(log n)

moving a node value up to the root value to maintain heap property or swapping nodes until a value is in the right position to maintain valid heap.

*O(h) where h = height = log n

93
Q

What is bubbling up?

A

Moving nodes up the heap

Swapping with parent

94
Q

Insert the numbers in a heap and draw each step then remove 24 and draw bubble steps.

A
95
Q

Insert the numbers in a heap and draw each step then remove 24 and draw bubble steps.

A
96
Q

Insert the numbers in a heap and draw each step then remove 24 and draw bubble steps.

A
97
Q

Insert the numbers in a heap and draw each step then remove 24 and draw bubble steps.

A
98
Q

Insert the numbers in a heap and draw each step then remove 24 and draw bubble steps.

A
99
Q

What data structure do we use to create a heap?

A

An array

We get the index of right and left children in the array using the formula:

left = parent * 2 + 1

right = parent * 2 + 2

parent = (index - 1 ) / 2

100
Q

HP How do we refactor the insert ( ) method in our Heap class?

A

Extract the bubbleUp ( ) method

into a private method

101
Q

How do we implement the bubbleUp( ) method in our Heap class?

A
102
Q

HP How do we implement remove ( ) method in our Heap class?

A

Using private helper methods:

largerChildIndex ( )

isValidParent ( )

rightChild ( )

leftChild ( )

rightChildIndex( )

leftChildIndex ( )

103
Q

What is the edge case issue with our largerChildIndex ( ) method?

A

How do we know if the node has children!

use helper methods:

hasLeftChild ( )

hasRightChild ( )

104
Q

What is the edge case issue with the isValidParent ( ) method?

A

Assumes node has left and right nodes!

105
Q

HP How can we refactor our remove ( ) method?

A

Extract bubbleDown ( ) logic into a private method

106
Q

What is heapSort ( ) ?

A

Using a heap to insert values

remove them in decending order (max Heap)

Why?

remove method removes root (max value)

next largest value bubbles up

continue removing the largest numbers in heap

107
Q

How do we sort in ascending ordering using heapSort ( )?

A

Change loop direction

108
Q

When is it best to use a heap to build a PriorityQueue?

A

For many inserts (enqueue) operations!

PriorityQueue using an array:

insert ( ) aka enqueue ( ) - O (n)

Have to shift items to insert at sorted index

remove ( ) aka dequeue ( ) - O (1 )

update the count pointer (count - 1)

PriorityQueue using a heap:

insert ( ) aka enqueue ( ) - O (log n)

bubbleUp ( ) length of tree, divide and conquer

remove ( ) aka dequeue ( ) - O (log n)

bubbleDown ( ) length of tree, divide and conquer

109
Q

How do we implement a PriorityQueue using a Heap?

A

Essentially, a wrapper around Heap class!

110
Q

How can we refactor our heapify ( ) method?

A

Popular interview question:

transform an array into a heap in place

Optimization:

lastParentIndex - only heapify parent nodes (not leaf nodes)

i = lastParentIndex - start recursion at deepest parent nodes (reverse recursions)

111
Q

How do we implement getKthLargest ( ) using a Heap?

A

Popular Interview Question:

Return the kth largest item in a list

Solution:

add items to heap

remove items until k - 1

return root (maxHeap)

112
Q

How can we implement isMaxHeap ( ) to determine if a given array of integers represents a max heap?

A
113
Q

How do we implement MinHeap using an array of nodes?

A

See MinHeap

114
Q

How do we implement MinPriorityQueue using a Heap?

A
115
Q

What are Tries?

A

Trees BUT not binary trees.

Each parent can have multiple nodes.

Powerful, overlooked data structures

aka

Digital, Radix, Prefix trees

116
Q

T What is an application for Tries?

A

Auto-completion

Why?

Not duplicating prefixes

Can extend branches

each node can have up to 26 letters!

Empty root (could be any letter)

117
Q

What are the various operations and run time complexities for Tries (Prefix, Radix, Digital)?

A

lookup ( ) - O(L)

walk down tree length of word (L)

insert ( ) - O(L)

walk tree, if character doesn’t exist, add it

remove ( ) - O(L)

*L is the length of the word in the Trie.

118
Q

How do we implement the TrieNode using a hash table as children?

A

Create services:

hasChild // returns boolean

addChild //adds key-value

getChild //returns value

getChildren //returns array []

hasChildren //returns boolean

removeChild //returns void

119
Q

How do we implement insert ( ) in our Trie class?

A
120
Q

How do we implement remove ( ) in our Trie class?

A
121
Q

How do we implement contains ( ) in our Trie class?

A
122
Q

How do we implement contains ( ) recursively?

A
123
Q

How do we implement findWords ( ) in our Trie (Autocompletion)?

A
124
Q

How do we implement countWords ( ) in a Trie?

A
125
Q

T How do we implement longestCommonPrefix ( ) in a Trie?

A

We add these words to a trie and walk down the trie.

If a node has more than one child, that’s where these words deviate.

Try this with “can”, “canada”, “care” and “cab”. You’ll see that these words deviate after “ca”.

So, we keep walking down the tree as long as the current node has only one child.

One edge case we need to count is when two words are in the same branch and don’t deviate.

For example “can” and “canada”.

In this case, we keep walking down to the end because every node (except the last node) has only one child.

But the longest common prefix here should be “can”, not “canada”.

So, we should find the shortest word in the list first.

The maximum number of characters we can include in the prefix should be equal to the length of the shortest word.

126
Q

How do we implement the TrieNode class in our Trie class using an array?

A

fieldOne: Char value

fieldTwo: TrieNodes [ALPHABET_SIZE] children

fieldThree: boolean isEndOfWord

Space complexity?

Every node has a 26 element array

this wastes a lot of memory!

127
Q

How do we implement the Trie class using an array for storing characters in each node?

A
128
Q

How can we refactor our TrieNode implementation using abstraction?

A

Create services in TrieNode class

129
Q

What is pre-order traversal in a Trie?

A

visit each root node first

then, visit children

Why?

Print all words in Trie

130
Q

What is post-order traversal in a Trie?

A

Visit children (leaf) nodes first

then, come up to visit root (parent) nodes

Why?

Delete a word!

Start with leaf nodes

131
Q

How do we implement pre-order traversal in our Trie class?

A

Why?

Print all words in Trie

132
Q

How do we implement post-order traversal?

A

Why?

Delete a word!

Start with leaf nodes

133
Q

How do we remove a word from a Trie?

A

Post-order traversal (begin at leaves)

remove isEndOfWord marker

if (!hasChild) remove it from Trie

134
Q

What are graphs?

A

Versatile data structures!

Consists of nodes (vertices) and edges

Nodes are called vertices (vertex).

Nodes can be connected to any other nodes.

Directly connected nodes are called adjacent nodes.

Connections between nodes are called edges

Edges can have weights to determine weight of connection.

.

135
Q

What don’t we have a limitation on in graphs?

A

We don’t have a limitation on how many connections or edges a node can have with other nodes.

136
Q

What are nodes called in a graph?

A

Vertices

137
Q

What are neighbors?

A

Two directly connected nodes

adject vertices (nodes) in a graph

Ex.

John & Bob are neighbors

138
Q

What are directed-graphs?

A

If edges have a direction

Ex. Twitter

Follow someone, they don’t follow back

139
Q

What are directed and undirected graphs?

A

Directed - following someone in twitter or instagram Undirected - facebook friends.

140
Q

What are real-world applications of graphs?

A

Anywhere we want to model relationship between objects!

Social networks - finding best friends (weights on edges)

GPS - shortest path between two nodes

find connections to other objects in a network

represent routers connected in a network

141
Q

What is the adjacency matrix?

A

A way to see how nodes are connected

Using a 2D array to represent edges in a graph

O (n^2) space complexity

142
Q

What is the adjacency List?

A

An Array of linkedLists (to represent connections)

Every element in the array has a LinkedList (bucket) containing adjacent nodes (neighbors)

HashTable to find index of a vertex (node)

143
Q

What is the runtime complexity of various operations using matrix vs. list approach in graphs?

A

K represents nodes in linkedList

V represents nodes in the graph

E represents connections (edges) in a graph

AddNode - don’t have to create a new array and copy elements in list

144
Q

Which approach is better (matrix vs. list) in implementing a graph?

A

Worst Case scenario (dense graph):

Use Adjacency Matrix

addEdge, removeEdge, queryEdge

Most applications (not very dense):

Use Adjacency List

addEdge, space complexity

145
Q

What is a dense graph?

A

A hypothetical (worst case):

When every vertex (node) is connected to every other node (beside itself)

146
Q

How do we implement addNode ( ), addEdge ( ) and Node class in our Graph?

A
147
Q

How do we implement removeNode ( ) and removeEdge ( ) in our Graph class?

A
148
Q

What is the difference between traversal in a graph vs. a tree?

A

There is no root node (can start anywhere)

the traversal ends when the node has no further connections (neighbors).

Other nodes are not visited = there isn’t a path to those nodes.

149
Q

What is the breadth-first graph traversal algorithm?

A

Visit a node and all it’s neighbors before going far in a graph.

150
Q

How is the breadth-first graph traversal algorithm implemented in software?

A

Using a queue.

The queue holds the address of the next node to visit (neighbor nodes).

As nodes are visited, neighbors are added to the queue to visit next.

Formula:

Visit the node, add its neighbors to the queue and continue until there are no neighbors (connections) left.

151
Q

When does the breadth-first graph traversal algorithm end?

A

When the queue is empty, the traversal is complete.

As soon, as the queue is “empty” the algorithm will stop.

152
Q

How do we implement traverseDepthFirst ( ) using recursion in our graph?

A

Use a set (check if visited neighbor nodes)

153
Q

What is the “call stack”?

A

Java Runtime environment stack

remembers values of arguments between method class

154
Q

How do we implement traverseDepthFirst ( ) using iteration?

A

Go deep, then loop to other neighbors

Use a Stack: neighbors

Why?

determine which node to visit next

Use a Set : visited nodes

Why?

To skip re-visiting already visited neighbors

155
Q

How do we implement traverseBreadthFirst ( ) in our graph?

A

We visit a node and all it’s neighbors before moving away from the node

Using:

HashMap - nodes, adjacency list

Queue - storing neighbor nodes (visit next)

Set - comparing queue w/ visited nodes

156
Q

What is the topological sorting algorithm?

A

Common Interview Question:

Implement the topological sorting algorithm

Implementation:

Depth-first traversal, find nodes w/out edges

these are nodes w/o depenencies (toward end)

Top hierarchy (nodes w/ edges) first!

157
Q

What are the applications of topological sorting in graphs?

A

Help us determine which order we should perform the tasks to ensure all dependencies are met.

When you have multiple tasks that have dependencies on each other to be completed.

158
Q

What must we know about topological sorting algorithms?

A

1. Different ways to topologically sort the same graph

2. Only work on graphs w/out a cycle (must be directed-acyclic graphs)

159
Q

How do we implement the topological sorting algorithm in software?

A

Using a stack, a set and a for loop.

Go deep into the graph to find the nodes that don’t have outgoing edges (children) then work our way up adding the node to our stack only if we have visited all the children or edges of the node.

  1. Depth-first traversal to go deep into the graph and find the node without any outgoing neighbors.
  2. Add node to a stack then move up the tree
160
Q

How do we detect a cycle in a graph?

A

Interview Question:

Write code to detect a cycle in a graph using colors!

red, blue, green = all, visiting, visited

Note:

Topological sorting doesn’t work on graphs w/ cycles!

Implementation:

Use three sets!

Set all - nodes in graph

Set visiting - nodes visited but not all children

Set visited - nodes visited and all children

HashTable to print cycle!

161
Q

How do we implement hasCycle ( ) using recursion in our Graph class?

A

Interview Question:

Write code to detect a cycle in a graph using colors!

Implementation:

Use three sets!

Set all - nodes in graph

Set visiting - nodes visited but not all children

Set visited - nodes visited and all children

162
Q

G What are weighted graphs?

A

Graphs whose edges have weights

Weights can represent anything!

Cost, distance, complexity, anything!

163
Q

What are common applications of weighted graphs?

A

Finding the shortest path between two nodes!

GPS - weights could be traffic, vertices locations!

164
Q

How do we implement a weighted graph using a non-OOP approach?

A

Two private classes:

Node, Edge

Two Maps:

HashMap nodes

HashMap> AdjacencyList

165
Q

G How do we refactor the weighted Graph into an OOP approach?

A

Replace HashTable> adjacencyList with ArrayList embedded into HashTable nodes

Add services: addEdge, getEdges to node

Why?

Object-Oriented Approach (not taught in Data Structures Textbooks)

Store edges in node objects

166
Q

What is Dijstra’s shortest path algorithm?

A

Greedy algorithm for getting the shortest path between two nodes on a graph.

Uses a table w/ assumptions

Calculate dist to start node and neighbors

find shortest path, record node to get there

167
Q

How do we implement getShortestDistance ( )?

A

Dijastras algorithm!

Implementation:

NodeEntry class w/ constructor

PriorityQueue

HashTable distances

Set visited

Breadth-first traversal (look at all neighbors)

How?

A weighted graph is used.

A HashMap is created with distances between one nodes and the other nodes.

The distance to the other nodes are unknown and initially set to a large value (Integer.MAX_VALUE)

As we move along the graph the distances are updated in the table as shorter paths are found.

The PriorityQueue helps us move to next closest neighbor (greedy algorithm)

168
Q

How can we refactor the getShortestPath ( ) in our WeightedGraph class?

A

Extract buildPath ( ) into a private method

169
Q

What is a minimum spanning tree in a graph?

A

We can convert a graph to a min spanning tree by calculating the min distance between nodes and removing all but that one edge between nodes. Should have n-1 edges. Using Prims algorithm can find the minimum spanning tree

170
Q

How do we represent how strong a connection is in a graph?

A

With a weight.

Edges can have a weight.

By measuring interactions between nodes we can assign higher weights.