Skip to content

Commit a8ffcf6

Browse files
committed
Day 58 Prim's algo and CTCI question
1 parent cc29611 commit a8ffcf6

File tree

6 files changed

+310
-26
lines changed

6 files changed

+310
-26
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,6 @@
3131

3232
#build director
3333
build/
34+
35+
#vim backup
36+
*.cpp~

.gitignore~

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Created by https://www.gitignore.io/api/c++
2+
### C++ ###
3+
# Compiled Object files
4+
*.slo
5+
*.lo
6+
*.o
7+
*.obj
8+
9+
# Precompiled Headers
10+
*.gch
11+
*.pch
12+
13+
# Compiled Dynamic libraries
14+
*.so
15+
*.dylib
16+
*.dll
17+
18+
# Fortran module files
19+
*.mod
20+
21+
# Compiled Static libraries
22+
*.lai
23+
*.la
24+
*.a
25+
*.lib
26+
27+
# Executables
28+
*.exe
29+
*.out
30+
*.app
31+
32+
#build director
33+
build/

README.md

+16-14
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
| Current Status| Stats |
66
| :------------: | :----------: |
7-
| Total Problems | 80 |
8-
| Current Streak | 57 |
9-
| Longest Streak | 57 ( August 17, 2015 - October 12, 2015 ) |
7+
| Total Problems | 82 |
8+
| Current Streak | 58 |
9+
| Longest Streak | 58 ( August 17, 2015 - October 13, 2015 ) |
1010

1111
</center>
1212

@@ -69,17 +69,18 @@ Include contains single header implementation of data structures and some algori
6969
### Cracking the coding interview problems
7070
| Problem | Solution |
7171
| :------------ | :----------: |
72-
| Problem 1 : Edition 6: Write an algorithm to determine whether a string has unique characters or not. Can we do it without using addtional data structures? | [1-1-hasUniqueChars.cpp](cracking_the_coding_interview_problems/1-1-hasUniqueChars.cpp)|
73-
| Problem 2 : Edition 5: Reverse a string when you are a pass a null terminated C string.|[1-2-edi5-reverseString.cpp ](cracking_the_coding_interview_problems/1-2-edi5-reverseString.cpp)|
74-
| Problem 2 : Edition 6: Given two strings, determine if one is permutation of other.|[1-2-perm-strings.cpp](cracking_the_coding_interview_problems/1-2-perm-strings.cpp)|
75-
| Problem 3 : Edition 5: Write an algorithm to remove duplicate chars from a string.|[1-3-edi5-removeDuplicates.cpp](cracking_the_coding_interview_problems/1-3-edi5-removeDuplicates.cpp)|
76-
| Problem 3 : Edition 6: URLify: Replace all the spaces in a string with '%20'. Preferebly Inplace |[1-3-URLify.cpp](cracking_the_coding_interview_problems/1-3-URLify.cpp)|
77-
| Problem 4 : Edition 6: Given a string, write a function to check if it is a permutation of a pallindrome.|[1-4-pallindrome-permutations.cpp ](cracking_the_coding_interview_problems/1-4-pallindrome-permutations.cpp)|
78-
| Problem 5 : Edition 6: There are three possible edits that can be performed on a string - Insert a char, Delete a char, Replace a char. Given two strings, determine if they are one or 0 edit away.|[1-5-one-edit-away.cpp ](cracking_the_coding_interview_problems/1-5-one-edit-away.cpp)|
79-
| Problem 6: Implement a method to perform basic string compression. Example string **aabcccccaaa** should be compressed to **a2b1c5a3**, however if compressed string is bigger than original string, return original string| [1-6-string-compression.cpp](cracking_the_coding_interview_problems/1-6-string-compression.cpp)|
80-
| Problem 7: Rotate the matrix clockwise( & anticlockwise) by 90 degrees| [1-7-matrix-rotation.cpp](cracking_the_coding_interview_problems/1-7-matrix-rotation.cpp)|
81-
| Problem 8: Write an algorithm such that if an element of MxN matrix is 0, its entire row and column is set to 0. | [1-8-zero-matrix.cpp](cracking_the_coding_interview_problems/1-8-zero-matrix.cpp)|
82-
| Problem 9: Given two strings s1 and s2, determine s2 is rotation of s1 using only one call to a function which checks whether one string is rotation of another.|[1-9-string-rotation.cpp](cracking_the_coding_interview_problems/1-9-string-rotation.cpp)|
72+
| Problem 1-1 : Edition 6: Write an algorithm to determine whether a string has unique characters or not. Can we do it without using addtional data structures? | [1-1-hasUniqueChars.cpp](cracking_the_coding_interview_problems/1-1-hasUniqueChars.cpp)|
73+
| Problem 1-2 : Edition 5: Reverse a string when you are a pass a null terminated C string.|[1-2-edi5-reverseString.cpp ](cracking_the_coding_interview_problems/1-2-edi5-reverseString.cpp)|
74+
| Problem 1-2 : Edition 6: Given two strings, determine if one is permutation of other.|[1-2-perm-strings.cpp](cracking_the_coding_interview_problems/1-2-perm-strings.cpp)|
75+
| Problem 1-3 : Edition 5: Write an algorithm to remove duplicate chars from a string.|[1-3-edi5-removeDuplicates.cpp](cracking_the_coding_interview_problems/1-3-edi5-removeDuplicates.cpp)|
76+
| Problem 1-3 : Edition 6: URLify: Replace all the spaces in a string with '%20'. Preferebly Inplace |[1-3-URLify.cpp](cracking_the_coding_interview_problems/1-3-URLify.cpp)|
77+
| Problem 1-4 : Edition 6: Given a string, write a function to check if it is a permutation of a pallindrome.|[1-4-pallindrome-permutations.cpp ](cracking_the_coding_interview_problems/1-4-pallindrome-permutations.cpp)|
78+
| Problem 1-5 : Edition 6: There are three possible edits that can be performed on a string - Insert a char, Delete a char, Replace a char. Given two strings, determine if they are one or 0 edit away.|[1-5-one-edit-away.cpp ](cracking_the_coding_interview_problems/1-5-one-edit-away.cpp)|
79+
| Problem 1-6: Implement a method to perform basic string compression. Example string **aabcccccaaa** should be compressed to **a2b1c5a3**, however if compressed string is bigger than original string, return original string| [1-6-string-compression.cpp](cracking_the_coding_interview_problems/1-6-string-compression.cpp)|
80+
| Problem 1-7: Rotate the matrix clockwise( & anticlockwise) by 90 degrees| [1-7-matrix-rotation.cpp](cracking_the_coding_interview_problems/1-7-matrix-rotation.cpp)|
81+
| Problem 1-8: Write an algorithm such that if an element of MxN matrix is 0, its entire row and column is set to 0. | [1-8-zero-matrix.cpp](cracking_the_coding_interview_problems/1-8-zero-matrix.cpp)|
82+
| Problem 1-9: Given two strings s1 and s2, determine s2 is rotation of s1 using only one call to a function which checks whether one string is rotation of another.|[1-9-string-rotation.cpp](cracking_the_coding_interview_problems/1-9-string-rotation.cpp)|
83+
| Problem 2-1: Remove duplicates from an *unsorted* linked list. What if no temporary buffer is allowed.|[2-1-remove-dups.cpp](cracking_the_coding_interview_problems/2-1-remove-dups.cpp)|
8384

8485
###Dynamic Programming Problems
8586
| Problem | Solution |
@@ -141,6 +142,7 @@ Include contains single header implementation of data structures and some algori
141142
| Depth First Traversal of a Graph | [dfsDemo.cpp](graph_problems/dfsDemo.cpp) |
142143
| Breadth First Traversal of a Graph | [bfsDemo.cpp](graph_problems/bfsDemo.cpp) |
143144
| calculate the shortest distance from the start position (Node S) to all of the other nodes in the graph using Dijkstra algorithm. | [dijkstra-shortest-reach.cpp](graph_problems/dijkstra-shortest-reach.cpp)|
145+
| Calculate total weight of Minimum Spanning Tree of a given graph ( sum of weights of edges which forms MST) using Prim's algorithm | [primsMST.cpp](graph_problems/primsMST.cpp)|
144146

145147
###Greedy Problems
146148
| Problem | Solution |

README.md~

+15-12
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
| Current Status| Stats |
66
| :------------: | :----------: |
7-
| Total Problems | 78 |
8-
| Current Streak | 56 |
9-
| Longest Streak | 56 ( August 17, 2015 - October 11, 2015 ) |
7+
| Total Problems | 82 |
8+
| Current Streak | 58 |
9+
| Longest Streak | 58 ( August 17, 2015 - October 13, 2015 ) |
1010

1111
</center>
1212

@@ -69,15 +69,18 @@ Include contains single header implementation of data structures and some algori
6969
### Cracking the coding interview problems
7070
| Problem | Solution |
7171
| :------------ | :----------: |
72-
| Problem 1 : Edition 6: Write an algorithm to determine whether a string has unique characters or not. Can we do it without using addtional data structures? | [1-1-hasUniqueChars.cpp](cracking_the_coding_interview_problems/1-1-hasUniqueChars.cpp)|
73-
| Problem 2 : Edition 5: Reverse a string when you are a pass a null terminated C string.|[1-2-edi5-reverseString.cpp ](cracking_the_coding_interview_problems/1-2-edi5-reverseString.cpp)|
74-
| Problem 2 : Edition 6: Given two strings, determine if one is permutation of other.|[1-2-perm-strings.cpp](cracking_the_coding_interview_problems/1-2-perm-strings.cpp)|
75-
| Problem 3 : Edition 5: Write an algorithm to remove duplicate chars from a string.|[1-3-edi5-removeDuplicates.cpp](cracking_the_coding_interview_problems/1-3-edi5-removeDuplicates.cpp)|
76-
| Problem 3 : Edition 6: URLify: Replace all the spaces in a string with '%20'. Preferebly Inplace |[1-3-URLify.cpp](cracking_the_coding_interview_problems/1-3-URLify.cpp)|
77-
| Problem 4 : Edition 6: Given a string, write a function to check if it is a permutation of a pallindrome.|[1-4-pallindrome-permutations.cpp ](cracking_the_coding_interview_problems/1-4-pallindrome-permutations.cpp)|
78-
| Problem 5 : Edition 6: There are three possible edits that can be performed on a string - Insert a char, Delete a char, Replace a char. Given two strings, determine if they are one or 0 edit away.|[1-5-one-edit-away.cpp ](cracking_the_coding_interview_problems/1-5-one-edit-away.cpp)|
79-
| Problem 6: Implement a method to perform basic string compression. Example string **aabcccccaaa** should be compressed to **a2b1c5a3**, however if compressed string is bigger than original string, return original string| [1-6-string-compression.cpp](cracking_the_coding_interview_problems/1-6-string-compression.cpp)|
80-
| Problem 7: Rotate the matrix clockwise( & anticlockwise) by 90 degrees| [1-7-matrix-rotation.cpp](cracking_the_coding_interview_problems/1-7-matrix-rotation.cpp)|
72+
| Problem 1-1 : Edition 6: Write an algorithm to determine whether a string has unique characters or not. Can we do it without using addtional data structures? | [1-1-hasUniqueChars.cpp](cracking_the_coding_interview_problems/1-1-hasUniqueChars.cpp)|
73+
| Problem 1-2 : Edition 5: Reverse a string when you are a pass a null terminated C string.|[1-2-edi5-reverseString.cpp ](cracking_the_coding_interview_problems/1-2-edi5-reverseString.cpp)|
74+
| Problem 1-2 : Edition 6: Given two strings, determine if one is permutation of other.|[1-2-perm-strings.cpp](cracking_the_coding_interview_problems/1-2-perm-strings.cpp)|
75+
| Problem 1-3 : Edition 5: Write an algorithm to remove duplicate chars from a string.|[1-3-edi5-removeDuplicates.cpp](cracking_the_coding_interview_problems/1-3-edi5-removeDuplicates.cpp)|
76+
| Problem 1-3 : Edition 6: URLify: Replace all the spaces in a string with '%20'. Preferebly Inplace |[1-3-URLify.cpp](cracking_the_coding_interview_problems/1-3-URLify.cpp)|
77+
| Problem 1-4 : Edition 6: Given a string, write a function to check if it is a permutation of a pallindrome.|[1-4-pallindrome-permutations.cpp ](cracking_the_coding_interview_problems/1-4-pallindrome-permutations.cpp)|
78+
| Problem 1-5 : Edition 6: There are three possible edits that can be performed on a string - Insert a char, Delete a char, Replace a char. Given two strings, determine if they are one or 0 edit away.|[1-5-one-edit-away.cpp ](cracking_the_coding_interview_problems/1-5-one-edit-away.cpp)|
79+
| Problem 1-6: Implement a method to perform basic string compression. Example string **aabcccccaaa** should be compressed to **a2b1c5a3**, however if compressed string is bigger than original string, return original string| [1-6-string-compression.cpp](cracking_the_coding_interview_problems/1-6-string-compression.cpp)|
80+
| Problem 1-7: Rotate the matrix clockwise( & anticlockwise) by 90 degrees| [1-7-matrix-rotation.cpp](cracking_the_coding_interview_problems/1-7-matrix-rotation.cpp)|
81+
| Problem 1-8: Write an algorithm such that if an element of MxN matrix is 0, its entire row and column is set to 0. | [1-8-zero-matrix.cpp](cracking_the_coding_interview_problems/1-8-zero-matrix.cpp)|
82+
| Problem 1-9: Given two strings s1 and s2, determine s2 is rotation of s1 using only one call to a function which checks whether one string is rotation of another.|[1-9-string-rotation.cpp](cracking_the_coding_interview_problems/1-9-string-rotation.cpp)|
83+
| Problem 2-1: Remove duplicates from an *unsorted* linked list. What if no temporary buffer is allowed.|[2-1-remove-dups.cpp](cracking_the_coding_interview_problems/2-1-remove-dups.cpp)|
8184

8285
###Dynamic Programming Problems
8386
| Problem | Solution |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/*
2+
* Cracking the coding interview edition 6
3+
* Problem 2-1 : Remove duplicates from an unsorted linked list.
4+
* Approach 1 : Naive approach of iterating and remove all further duplicates of current node. Space complexity O(1) & time complexity O(n^2)
5+
* Approach 2: Use a hash table
6+
*/
7+
8+
9+
#include <iostream>
10+
#include <unordered_map>
11+
#include <random>
12+
13+
14+
struct Node {
15+
int data = 0;
16+
Node * next = nullptr;
17+
};
18+
19+
void insert( Node * & head, int data )
20+
{
21+
Node * newNode = new Node;
22+
newNode->data = data;
23+
newNode->next = head;
24+
head = newNode;
25+
}
26+
27+
void printList( Node * head ) {
28+
while( head ) {
29+
std::cout << head->data << " ";
30+
head = head->next;
31+
}
32+
std::cout << std::endl;
33+
}
34+
35+
//generate a random int between min and max
36+
static inline int random_range(const int min, const int max) {
37+
std::random_device rd;
38+
std::mt19937 mt(rd());
39+
std::uniform_int_distribution<int> distribution(min, max);
40+
return distribution(mt);
41+
}
42+
43+
44+
// Method 1
45+
//space complexity O(1)
46+
// time complexity O(n^2)
47+
void removeDuplicates( Node * head ) {
48+
if ( head == nullptr || ( head && (head->next == nullptr))) {
49+
return;
50+
}
51+
Node * curr = head;
52+
while(curr) {
53+
Node * runner = curr;
54+
while (runner->next != nullptr) {
55+
if (runner->next->data == curr->data) {
56+
runner->next = runner->next->next;
57+
} else {
58+
runner = runner->next;
59+
}
60+
}
61+
curr = curr->next;
62+
}
63+
}
64+
65+
// Method 2
66+
// space complexity - O(n)
67+
// time complexity - O(n)
68+
void removeDuplicates1( Node * head ) {
69+
if ( head == nullptr || ( head && (head->next == nullptr) )) {
70+
return ;
71+
}
72+
std::unordered_map<int, int> node_map;
73+
Node * prev = head;
74+
Node * curr = head->next;
75+
node_map[head->data] = 1;
76+
while( curr != nullptr ) {
77+
while (curr && node_map.find(curr->data) != node_map.end()) {
78+
curr = curr->next;
79+
}
80+
prev->next = curr;
81+
prev = curr;
82+
if (curr) {
83+
node_map[curr->data] = 1;
84+
curr = curr->next;
85+
}
86+
}
87+
}
88+
89+
90+
91+
int main() {
92+
std::cout << "Method 1 : \n";
93+
Node * head = nullptr;
94+
for ( int i = 0; i < 10; ++i ) {
95+
insert(head, random_range(1,7));
96+
}
97+
printList(head);
98+
removeDuplicates(head);
99+
printList(head);
100+
101+
std::cout << "Method 2 : \n";
102+
Node * head1 = nullptr;
103+
for ( int i = 0; i < 10; ++i ) {
104+
insert(head1, random_range(1,7));
105+
}
106+
printList(head1);
107+
removeDuplicates1(head1);
108+
printList(head1);
109+
110+
111+
}

graph_problems/primsMST.cpp

+132
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
/**
2+
* Minimum spanning tree using Prim's algorithm.
3+
* Approach greedy
4+
* Calculate the weight of minimum spanning tree(sum of weight of edges of MST)
5+
* and print the edges which makes MST.
6+
* Input format:
7+
* ROW 1 :: V - number of vertices, E - number of Edges.
8+
* Next E lines give details of each edge in format x y w.
9+
* where x is start of edge, y is end of edge and w is weight of xy edge
10+
* After that, S - Index of the starting point of finding the MST.
11+
* all the input is not 0 indexed.
12+
*/
13+
14+
15+
16+
#include <iostream>
17+
#include <limits>
18+
19+
const int MIN = std::numeric_limits<int>::min();
20+
const int MAX = std::numeric_limits<int>::max();
21+
22+
23+
/**
24+
* Print the Minimum spanning tree
25+
*/
26+
void printMST( int ** graph, int * MST, int V ) {
27+
std::cout << " Edge Weight \n";
28+
for ( int v = 0; v < V; ++v ) {
29+
if (MST[v] != -1 && graph[v][MST[v]] != -1 ) {
30+
std::cout << v+1 << "<-->" << MST[v]+1 << " " << graph[v][MST[v]] << std::endl;
31+
}
32+
}
33+
}
34+
35+
36+
/**
37+
* minKey
38+
* returns the index of the vertex which is not yet part of MST
39+
* and has minimum key.
40+
*/
41+
42+
int minKey( int * keys, bool * inMST, int V ) {
43+
int min = MAX, minIndex;
44+
for ( int v = 0; v < V; ++v ) {
45+
if ( inMST[v] == false && min > keys[v] ) {
46+
minIndex = v;
47+
min = keys[v];
48+
}
49+
}
50+
return minIndex;
51+
}
52+
53+
54+
/**
55+
* primsMSTWeight
56+
* returns the weight of the minimum spanning tree of the graph
57+
* Args:
58+
* graph: adjacency matrix of the graph
59+
* V : Total number of vertices in the graph
60+
* S : Starting index of MST
61+
*/
62+
int primsMSTWeight( int ** graph, int V, int S, int * MST)
63+
{
64+
int * key = new int[V];
65+
bool * inMST = new bool[V];
66+
67+
for ( int v = 0; v < V; ++v ) {
68+
inMST[v] = false;
69+
key[v] = MAX;
70+
}
71+
72+
key[S] = 0;
73+
for ( int count = 0; count < V-1; ++count ) {
74+
int u = minKey(key, inMST, V);
75+
inMST[u] = true;
76+
for ( int v = 0; v < V; ++v ) {
77+
if ( (graph[u][v] != -1) && (inMST[v] == false) && (key[v] > graph[u][v]) ) {
78+
key[v] = graph[u][v];
79+
MST[v] = u;
80+
}
81+
}
82+
}
83+
84+
int sum = 0;
85+
for ( int v = 0 ;v < V; ++v ) {
86+
if ( MST[V] != -1 && graph[v][MST[v]] != -1 ) {
87+
sum += graph[v][MST[v]];
88+
}
89+
}
90+
delete[] key;
91+
delete[] inMST;
92+
return sum;
93+
}
94+
95+
96+
int main()
97+
{
98+
int V, E, x, y, w, S;
99+
/**
100+
* V -- number of vertices
101+
* E -- number of edges
102+
* xy-- edge with endpoints x and y
103+
* w -- weight of edge
104+
* S -- Starting index
105+
*/
106+
107+
std::cin >> V >> E;
108+
int ** graph = new int*[V];
109+
for ( int v = 0; v < V; ++v ) {
110+
graph[v] = new int[V];
111+
for ( int w = 0; w < V; ++w ) {
112+
graph[v][w] = -1;
113+
}
114+
}
115+
116+
for ( int i = 0; i < E; ++i ) {
117+
std::cin >> x >> y >> w;
118+
if ( graph[x-1][y-1] == -1 ||
119+
( (graph[x-1][y-1] > 0) && (graph[x-1][y-1] > w ))) {
120+
graph[x-1][y-1] = w;
121+
graph[y-1][x-1] = w;
122+
}
123+
}
124+
125+
std::cin >> S;
126+
int * MST = new int[V];
127+
MST[S-1] = -1;
128+
std::cout << "Min Spanning tree weight " << primsMSTWeight(graph, V, S-1, MST) << std::endl;
129+
std::cout << "Min Spanning tree:\n";
130+
printMST(graph, MST, V);
131+
return 0;
132+
}

0 commit comments

Comments
 (0)