Here is the code which will work on all unix systems and give all the words that can be formed in wordament game.
Few highlights for the code :
1) Code can be easily modified to give only big words for more points.
2) Also longer words are printed first. This feature can also be easily changed.
3) To compile the code just use g++ compiler. (g++ test.cpp).
4) and run it using ./a.out
5) input the wordament game in row first format.
6) This code was written using code from g4g site.
7) I combined the code given in "g4g boggle solver" and "g4g tries" and combined them to solve wordament.
Code :
#include<iostream>
#include<cstring>
#include <vector>
#include <fstream>
#include <algorithm>
#include <pthread.h>
using namespace std;
#define M 4
#define N 4
#define MAX 15
#define MIN 7
struct TrieNode *dictionary;// = getNode();
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)
// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
string boggle[M][N];// = {{'G','I','Z'},
// trie node
vector<string> ans;
struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
// isLeaf is true if the node represents
// end of a word
bool isLeaf;
};
// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
struct TrieNode *pNode = NULL;
pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode));
if (pNode)
{
int i;
pNode->isLeaf = false;
for (i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}
return pNode;
}
// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(struct TrieNode *root, string key)
{
int level;
int length = key.size();
int index;
struct TrieNode *pCrawl = root;
for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->isLeaf = true;
}
// Returns true if key presents in trie, else false
bool search(struct TrieNode *root, string key)
{
int level;
int length = key.size();
int index;
struct TrieNode *pCrawl = root;
for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);
if (!pCrawl->children[index])
return false;
pCrawl = pCrawl->children[index];
}
return (pCrawl != NULL && pCrawl->isLeaf);
}
// A given function to check if a given string is present in
// dictionary. The implementation is naive for simplicity. As
// per the question dictionary is givem to us.
bool isWord(string &str)
{
if (search(dictionary, str) != 0)
return true;
return false;
}
// A recursive function to print all words present on boggle
void findWordsUtil(bool visited[M][N], int i,
int j, string &str, int size)
{
// Mark current cell as visited and append current character
// to str
//int size;
visited[i][j] = true;
str = str + boggle[i][j];
size = size+boggle[i][j].size();
// If str is present in dictionary, then print it
if (size<= MAX && size>=MIN && isWord(str))
ans.push_back(str);//cout << str << endl;
// Traverse 8 adjacent cells of boggle[i][j]
for (int row=i-1; row<=i+1 && row<M; row++)
for (int col=j-1; col<=j+1 && col<N; col++)
if (row>=0 && col>=0 && !visited[row][col])
findWordsUtil(visited, row, col, str, size);
// Erase current character from string and mark visited
// of current cell as false
str.erase(str.length()-boggle[i][j].size());
size = size - boggle[i][j].size();
visited[i][j] = false;
}
// Prints all words present in dictionary.
void findWords() {
bool visited[M][N] = {{false}};
string str = "";
for (int i=0; i<M; i++)
for (int j=0; j<N; j++)
findWordsUtil(visited, i, j, str, 0);
}
int all_chars(string s) {
int t = s.size();
for (int i = 0; i<t; i++) {
if (!(s[i] >= 'a' && s[i] <= 'z'))
return 0;
}
return 1;
}
void load_dictionary() {
string line;
int n = 0;
ifstream myfile("/usr/share/dict/words");
dictionary = getNode();
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
//std::transform(line.begin(), line.end(), line.begin(), ::tolower);
//dictionary.push_back(line);
if (all_chars(line) && line.size()<=MAX && line.size()>=MIN) {
insert(dictionary, line);
n++;
}
}
myfile.close();
}
cout <<"words added = "<<n<<endl;
}
void enter_boog(string boggle[M][N]) {
int i,j;
for (i= 0; i<M; i++) {
for (j = 0; j<N; j++) {
cin>>boggle[i][j];
}
}
}
bool compare(string s1, string s2) {
int i = s1.size();
int j = s2.size();
if ( i != j)
return i > j;
else
return (s1[0] - s2[0] > 0);
}
void display_words() {
sort(ans.begin(), ans.end(), compare);
for (int i=0; i<ans.size(); i++) {
cout<<ans[i]<<endl;
}
}
// Driver program to test above function
int main()
{
load_dictionary();
while (1) {
cout<<"enter boggle matrix";
enter_boog(boggle);
for (int i= 0; i<M; i++) {
for (int j = 0; j<N; j++) {
cout<<boggle[i][j]<<" ";
}
cout<<endl;
}
cout << "Following words of dictionary are present\n";
findWords();
display_words();
ans.resize(0);
}
return 0;
}
Showing posts with label Geeksforgeeks. Show all posts
Showing posts with label Geeksforgeeks. Show all posts
Wednesday, June 7, 2017
Sunday, April 16, 2017
Minimum Path Sum in C++ using tabulation (Dynamic Programming)
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int row = grid.size();
int col = grid[0].size();
vector<vector<int>> v(row, vector<int>(col,0));
v[0][0] = grid[0][0];
for (int i = 1; i< row; i++)
v[i][0] = grid[i][0] + v[i-1][0];
for (int i = 1; i< col; i++)
v[0][i] = grid[0][i] + v[0][i-1];
for (int i = 1; i<row; i++) {
for (int j = 1; j < col; j++) {
v[i][j] = grid[i][j] + min (v[i-1][j], v[i][j-1]);
}
}
return v[row-1][col-1];
}
};
Coin Change problem in C++ using tabulation method dynamic programming
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return
-1
.
Example 1:
coins =
return
coins =
[1, 2, 5]
, amount = 11
return
3
(11 = 5 + 5 + 1)
Example 2:
coins =
return
coins =
[2]
, amount = 3
return
-1
.
Note:
You may assume that you have an infinite number of each kind of coin.
You may assume that you have an infinite number of each kind of coin.
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int n = coins.size();
vector<vector<int>> v(n+1, vector<int>(amount+1, 0));
for (int i = 0; i<=n; i++)
v[i][0] = 0;
for (int i = 0; i<= amount; i++)
v[0][i] = INT_MAX;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= amount; j++) {
if (j>=coins[i-1] && v[i][j-coins[i-1]] < INT_MAX)
v[i][j] = min(v[i-1][j], v[i][j-coins[i-1]]+1);
else
v[i][j] = v[i-1][j];
}
}
return (v[n][amount]<INT_MAX)?v[n][amount]:-1;
}
};
Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
b) Delete a character
c) Replace a character
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.size();
int len2 = word2.size();
vector<vector<int>> v (len1+1, vector<int>(len2+1, 0));
if (len1 == 0) return len2;
if (len2 == 0) return len1;
for (int i = 0; i< len1+1; i++) {
for (int j = 0; j< len2+1; j++) {
if (i == 0) v[i][j] = j;
else if (j == 0) v[i][j] = i;
else if (word1[i-1] == word2[j-1]) v[i][j] = v[i-1][j-1];
else v[i][j] = 1+ min(min(v[i-1][j], v[i][j-1]), v[i-1][j-1]);
}
}
return v[len1][len2];
}
};
Longest Consecutive Sequence c++
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
Given
[100, 4, 200, 1, 3, 2]
,The longest consecutive elements sequence is
[1, 2, 3, 4]
. Return its length: 4
.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int max = 0;
int cnt = 0;
if (nums.size() == 0 ) return 0;
sort(nums.begin(), nums.end());
for (int i = 0; i< nums.size(); i++) {
if (nums[i]+1 == nums[i+1]) {
cnt++;
} else if (nums[i+1] > nums[i]){
if (cnt>max) max = cnt;
cnt = 0;
}
}
if (cnt>max) max = cnt;
return max+1;
}
};
Longest Substring Without Repeating Characters C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void util (string &s, int & max, int start, int end) {
vector<int> arr(256,-1);
int cnt = 0;
int i;
if (start >= end) return;
for (i = start; i<end; i++) {
if (arr[s[i]] == -1) {
cnt++;
arr[s[i]] = i;
} else {
break;
}
}
if (cnt>max) max = cnt;
arr.clear();
if (i<end)
util (s, max, arr[s[i]]+1, end);
}
int lengthOfLongestSubstring(string s) {
int max = 0;
util(s, max, 0, s.size());
return max;
}
int main() {
string s = "";
cout <<lengthOfLongestSubstring(s);
return 0;
}
#include <string>
#include <vector>
using namespace std;
void util (string &s, int & max, int start, int end) {
vector<int> arr(256,-1);
int cnt = 0;
int i;
if (start >= end) return;
for (i = start; i<end; i++) {
if (arr[s[i]] == -1) {
cnt++;
arr[s[i]] = i;
} else {
break;
}
}
if (cnt>max) max = cnt;
arr.clear();
if (i<end)
util (s, max, arr[s[i]]+1, end);
}
int lengthOfLongestSubstring(string s) {
int max = 0;
util(s, max, 0, s.size());
return max;
}
int main() {
string s = "";
cout <<lengthOfLongestSubstring(s);
return 0;
}
Longest increasing sub-sequence in C++
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = 0, max = 0;
int n = nums.size();
vector<int> L(n,1);
for (int i = 0; i< n; i++) {
for (int j = i+1; j<n; j++) {
if (nums[j]>nums[i] && L[j]<L[i]+1) {
L[j] = L[i]+1;
}
}
}
for (int i = 0; i<n; i++) {
if (max<L[i]) max = L[i];
}
return max;
}
};
public:
int lengthOfLIS(vector<int>& nums) {
int len = 0, max = 0;
int n = nums.size();
vector<int> L(n,1);
for (int i = 0; i< n; i++) {
for (int j = i+1; j<n; j++) {
if (nums[j]>nums[i] && L[j]<L[i]+1) {
L[j] = L[i]+1;
}
}
}
for (int i = 0; i<n; i++) {
if (max<L[i]) max = L[i];
}
return max;
}
};
Friday, February 24, 2017
Saving contacts information using tries
Implementation for : https://www.hackerrank.com/challenges/ctci-contacts
Code :
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
struct trie {
int isleaf;
int child_cnt;
trie * t[26];
};
int index(char c) {
return c-'a';
}
trie * new_node() {
trie * node = (trie *)malloc(sizeof(trie));
for (int i = 0; i<26; i++) {
node->t[i] = NULL;
}
node->isleaf = 0;
int child_cnt = 0;
return node;
}
void add (trie * root, string s) {
int len = s.size();
for (int i = 0; i< len; i++) {
if (root->t[index(s[i])] == NULL) {
root->t[index(s[i])] = new_node();
}
root->t[index(s[i])]->child_cnt++;
root = root->t[index(s[i])];
}
root->isleaf = 1;
}
int find(trie *root, string s) {
int len = s.size();
for (int i = 0; i< len; i++) {
if (root->t[index(s[i])] == NULL) {
return 0;
}
root = root->t[index(s[i])];
}
if (root) {
return root->child_cnt;
}
return 0;
}
int main(){
int n;
cin >> n;
trie * root = new_node();
for(int a0 = 0; a0 < n; a0++){
string op;
string contact;
cin >> op >> contact;
if (op == "add") {
add(root, contact);
} else {
cout<<(find(root, contact))<<endl;
}
}
return 0;
}
Code :
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
struct trie {
int isleaf;
int child_cnt;
trie * t[26];
};
int index(char c) {
return c-'a';
}
trie * new_node() {
trie * node = (trie *)malloc(sizeof(trie));
for (int i = 0; i<26; i++) {
node->t[i] = NULL;
}
node->isleaf = 0;
int child_cnt = 0;
return node;
}
void add (trie * root, string s) {
int len = s.size();
for (int i = 0; i< len; i++) {
if (root->t[index(s[i])] == NULL) {
root->t[index(s[i])] = new_node();
}
root->t[index(s[i])]->child_cnt++;
root = root->t[index(s[i])];
}
root->isleaf = 1;
}
int find(trie *root, string s) {
int len = s.size();
for (int i = 0; i< len; i++) {
if (root->t[index(s[i])] == NULL) {
return 0;
}
root = root->t[index(s[i])];
}
if (root) {
return root->child_cnt;
}
return 0;
}
int main(){
int n;
cin >> n;
trie * root = new_node();
for(int a0 = 0; a0 < n; a0++){
string op;
string contact;
cin >> op >> contact;
if (op == "add") {
add(root, contact);
} else {
cout<<(find(root, contact))<<endl;
}
}
return 0;
}
Tuesday, January 31, 2017
Runtime complexity of STL Map and Multimap
Runtime complexity of STL Map and Multimap
Maps can be thought of as generalized vectors. They allow map[key] = value for any kind of key, not just integers. Maps are often called associative tables in other languages, and are incredibly useful. They're even useful when the keys are integers, if you have very sparse arrays, i.e., arrays where almost all elements are one value, usually 0.
Maps are implemented with balanced binary search trees, typically red-black trees. Thus, they provide logarithmic storage and retrieval times. Because they use search trees, maps need a comparison predicate to sort the keys. operator<() will be used by default if none is specified a construction time.
Maps store <key, value> pair's. That's what map iterators will return when dereferenced. To get the value pointed to by an iterator, you need to say
Maps can be thought of as generalized vectors. They allow map[key] = value for any kind of key, not just integers. Maps are often called associative tables in other languages, and are incredibly useful. They're even useful when the keys are integers, if you have very sparse arrays, i.e., arrays where almost all elements are one value, usually 0.
Maps are implemented with balanced binary search trees, typically red-black trees. Thus, they provide logarithmic storage and retrieval times. Because they use search trees, maps need a comparison predicate to sort the keys. operator<() will be used by default if none is specified a construction time.
Maps store <key, value> pair's. That's what map iterators will return when dereferenced. To get the value pointed to by an iterator, you need to say
(*mapIter).secondUsually though you can just use map[key] to get the value directly.
Warning: map[key] creates a dummy entry for key if one wasn't in the map before. Use map.find(key) if you don't want this to happen.multimaps are like map except that they allow duplicate keys. map[key] is not defined for multimaps. Instead you use lower_bound() and upper_bound(), or equal_range(), to get the iterators for the beginning and end of the range of values stored for the key. To insert a new entry, use map.insert(pair<key_type, value_type>(key, value)).
Header
#include <map>Constructors
map< key_type, value_type, key_compare > m; | Make an empty map. key_compare should be a binary predicate for ordering the keys. It's optional and will default to a function that uses operator<. | O(1) |
map< key_type, value_type, key_compare > m(begin, end); | Make a map and copy the values from begin to end. | O(n log n) |
Accessors
m[key] | Return the value stored for key. This adds a default value if key not in map. | O(log n) |
m.find(key) | Return an iterator pointing to a key-value pair, or m.end() if key is not in map. | O(log n) |
m.lower_bound(key) | Return an iterator pointing to the first pair containing key, or m.end() if key is not in map. | O(log n) |
m.upper_bound(key) | Return an iterator pointing one past the last pair containing key, or m.end() if key is not in map. | O(log n) |
m.equal_range(key) | Return a pair containing the lower and upper bounds for key. This may be more efficient than calling those functions separately. | O(log n) |
m.size(); | Return current number of elements. | O(1) |
m.empty(); | Return true if map is empty. | O(1) |
m.begin() | Return an iterator pointing to the first pair. | O(1) |
m.end() | Return an iterator pointing one past the last pair. | O(1) |
Modifiers
m[key] = value; | Store value under key in map. | O(log n) |
m.insert(pair) | Inserts the <key, value> pair into the map. Equivalent to the above operation. | O(log n) |
Labels:
C/C++,
CODING,
Geeksforgeeks,
Interviews,
Programming,
STL
Runtime complexity of STL Set and Multiset
Runtime complexity of STL Set and Multiset
Anything stored in a set has to have a comparison predicate. This will default to whatever operator<() has been defined for the item you're storing. Alternatively, you can specify a predicate to use when constructing the set.
Set and Multiset
Sets store objects and automatically keep them sorted and quick to find. In a set, there is only one copy of each objects. multisets are declared and used the same as sets but allow duplicate elements.Anything stored in a set has to have a comparison predicate. This will default to whatever operator<() has been defined for the item you're storing. Alternatively, you can specify a predicate to use when constructing the set.
Header
#include <set>Constructors
set< type, compare > s; | Make an empty set. compare should be a binary predicate for ordering the set. It's optional and will default to a function that uses operator<. | O(1) |
set< type, compare > s(begin, end); | Make a set and copy the values from begin to end. | O(n log n) |
Accessors
s.find(key) | Return an iterator pointing to an occurrence of key in s, or s.end() if key is not in s. | O(log n) |
s.lower_bound(key) | Return an iterator pointing to the first occurrence of an item in s not less than key, or s.end() if no such item is found. | O(log n) |
s.upper_bound(key) | Return an iterator pointing to the first occurrence of an item greater than key in s, or s.end() if no such item is found. | O(log n) |
s.equal_range(key) | Returns pair<lower_bound(key), upper_bound(key)>. | O(log n) |
s.count(key) | Returns the number of items equal to key in s. | O(log n) |
s.size(); | Return current number of elements. | O(1) |
s.empty(); | Return true if set is empty. | O(1) |
s.begin() | Return an iterator pointing to the first element. | O(1) |
s.end() | Return an iterator pointing one past the last element. | O(1) |
Modifiers
s.insert(iterator, key) | Inserts key into s. iterator is taken as a "hint" but key will go in the correct position no matter what. Returns an iterator pointing to where key went. | O(log n) |
s.insert(key) | Inserts key into s and returns a pair<iterator, bool>, where iterator is where key went and bool is true if key was actually inserted, i.e., was not already in the set. | O(log n) |
Labels:
C/C++,
CODING,
Geeksforgeeks,
Interviews,
Programming,
STL
Runtime complexity of STL priority Queue
Priority Queue
In the C++ STL, a priority queue is a container adaptor. That means there is no primitive priorty queue data structure. Instead, you create a priority queue from another container, like a deque, and the priority queue's basic operations will be implemented using the underlying container's operations.Priority queues are neither first-in-first-out nor last-in-first-out. You push objects onto the priority queue. The top element is always the "biggest" of the elements currently in the priority queue. Biggest is determined by the comparison predicate you give the priority queue constructor.
If that predicate is a "less than" type predicate, then biggest means largest.
If it is a "greater than" type predicate, then biggest means smallest.
Runtime complexity of STL priority Queue
Header
#include <queue> -- not a typo!Constructors
priority_queue<T, container<T>, comparison<T> > q; | Make an empty priority queue using the given container to hold values, and comparison to compare values. container defaults to vector<T> and comparison defaults to less<T>. | O(1) |
Accessors
q.top(); | Return the "biggest" element. | O(1) |
q.size(); | Return current number of elements. | O(1) |
q.empty(); | Return true if priority queue is empty. | O(1) |
Modifiers
q.push(value); | Add value to priority queue. | O(log n) |
q.pop(); | Remove biggest value. | O(log n) |
Labels:
C/C++,
CODING,
Geeksforgeeks,
Interviews,
Programming,
STL
Runtime complexity of STL Queue
Runtime complexity of STL Queue
Queue
In the C++ STL, a queue is a container adaptor. That means there is no primitive queue data structure. Instead, you create a queue from another container, like a list, and the queue's basic operations will be implemented using the underlying container's operations.
Don't confuse a queue
with a deque.
Header
#include <queue>Constructors
queue< container<T> > q; | Make an empty queue. | O(1) |
Accessors
q.front(); | Return the front element. | O(1) |
q.back(); | Return the rear element. | O(1) |
q.size(); | Return current number of elements. | O(1) |
q.empty(); | Return true if queue is empty. | O(1) |
Modifiers
q.push(value); | Add value to end. | Same for push_back() for underlying container. |
q.pop(); | Remove value from front. | O(1) |
Labels:
C/C++,
CODING,
Geeksforgeeks,
Interviews,
Programming,
STL
Runtime complexity of STL Stack
Runtime complexity of STL Stack
Stack
In the C++ STL, a stack is a container adaptor. That means there is no primitive stack data structure. Instead, you create a stack from another container, like a list, and the stack's basic operations will be implemented using the underlying container's operations.Header
#include <stack>Constructors
stack< container<T> > s; | Make an empty stack. | O(1) |
Accessors
s.top(); | Return the top element. | O(1) |
s.size(); | Return current number of elements. | O(1) |
s.empty(); | Return true if stack is empty. | O(1) |
Modifiers
s.push(value); | Push value on top. | Same as push_back() for underlying container. |
s.pop(); | Pop value from top. | O(1) |
Labels:
C/C++,
CODING,
Geeksforgeeks,
Interviews,
Programming,
STL
Runtime complexity of STL Deque
Runtime complexity of STL Deque
Constructors
deque<T> d; | Make an empty deque. | O(1) |
deque<T> d(n); | Make a deque with N elements. | O(n) |
deque<T> d(n, value); | Make a deque with N elements, initialized to value. | O(n) |
deque<T> d(begin, end); | Make a deque and copy the values from begin to end. | O(n) |
Accessors
d[i]; | Return (or set) the I'th element. | O(1) |
d.at(i); | Return (or set) the I'th element, with bounds checking. | O(1) |
d.size(); | Return current number of elements. | O(1) |
d.empty(); | Return true if deque is empty. | O(1) |
d.begin(); | Return random access iterator to start. | O(1) |
d.end(); | Return random access iterator to end. | O(1) |
d.front(); | Return the first element. | O(1) |
d.back(); | Return the last element. | O(1) |
Modifiers
d.push_front(value); | Add value to front. | O(1) (amortized) |
d.push_back(value); | Add value to end. | O(1) (amortized) |
d.insert(iterator, value); | Insert value at the position indexed by iterator. | O(n) |
d.pop_front(); | Remove value from front. | O(1) |
d.pop_back(); | Remove value from end. | O(1) |
d.erase(iterator); | Erase value indexed by iterator. | O(n) |
d.erase(begin, end); | Erase the elements from begin to end. | O(n) |
Labels:
C/C++,
CODING,
Geeksforgeeks,
Interviews,
Programming,
STL
Runtime complexity of STL vector
Runtime complexity of STL vector
Vector
Header
#include <vector>Constructors
vector<T> v; | Make an empty vector. | O(1) |
vector<T> v(n); | Make a vector with N elements. | O(n) |
vector<T> v(n, value); | Make a vector with N elements, initialized to value. | O(n) |
vector<T> v(begin, end); | Make a vector and copy the elements from begin to end. | O(n) |
Accessors
v[i]; | Return (or set) the I'th element. | O(1) |
v.at(i); | Return (or set) the I'th element, with bounds checking. | O(1) |
v.size(); | Return current number of elements. | O(1) |
v.empty(); | Return true if vector is empty. | O(1) |
v.begin(); | Return random access iterator to start. | O(1) |
v.end(); | Return random access iterator to end. | O(1) |
v.front(); | Return the first element. | O(1) |
v.back(); | Return the last element. | O(1) |
v.capacity(); | Return maximum number of elements. | O(1) |
Modifiers
v.push_back(value); | Add value to end. | O(1) (amortized) |
v.insert(iterator, value); | Insert value at the position indexed by iterator. | O(n) |
v.pop_back(); | Remove value from end. | O(1) |
v.erase(iterator); | Erase value indexed by iterator. | O(n) |
v.erase(begin, end); | Erase the elements from begin to end. | O(n) |
Labels:
C/C++,
CODING,
Geeksforgeeks,
Interviews,
Programming,
STL
Journey to the Moon
My Solution to "Journey to the Moon" hackerrank question. All testcases pass.
https://www.hackerrank.com/challenges/journey-to-the-moon
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <ctime>
#include <cassert>
using namespace std;
int connected (int a, int b, vector<vector<int>> & v) {
queue<int> q;
vector<int> v1(v.size(), 0);
for (int i = 0; i< v[a].size(); i++) {
q.push(v[a][i]);
}
v1[a] = 1;
while(!q.empty()) {
if (q.front() == b) return 1;
if (v1[q.front()] == 0) {
for (int i = 0; i< v[q.front()].size(); i++) {
q.push(v[q.front()][i]);
}
}
v1[q.front()] = 1;
q.pop();
}
return 0;
}
int main()
{
int N, I;
int c = 0;
long long c1 = 0;
cin >> N >> I;
vector<vector<int> > pairs(N);
vector<vector<int> > country;
vector<int> v(N,0);
vector<int> v1(N,0);
for (int i = 0; i < I; ++i) {
int a, b;
cin >> a >> b;
pairs[a].push_back(b);
pairs[b].push_back(a);
}
long long result = 0;
/** Write code to compute the result using N,I,pairs **/
for (int i = 0; i < N; ++i) {
if (v[i] == 0 && pairs[i].size() > 0) {
vector<int> v2(0);
country.push_back(v2);
country[c].push_back(i);
v1[i] = 1;
for (int j = 0; j<pairs[i].size(); j++) {
if (v1[pairs[i][j]] == 0)
country[c].push_back(pairs[i][j]);
v1[pairs[i][j]] = 1;
}
v[i] = 1;
for(int k = 0; k<country[c].size(); k++) {
if (v[country[c][k]] == 0) {
for (int j = 0; j<pairs[country[c][k]].size(); j++) {
if (v1[pairs[country[c][k]][j]] == 0)
country[c].push_back(pairs[country[c][k]][j]);
v1[pairs[country[c][k]][j]] = 1;
}
}
v[country[c][k]] = 1;
}
c++;
//cout<<"here";
} else {
if (pairs[i].size() == 0) {
//vector<int> v2(0);
//country.push_back(v2);
//country[c].push_back(i);
c1++;
}
}
}
for (int i = 0; i<country.size(); i++) {
for (int j = i +1; j<country.size(); j++) {
result = result + country[i].size() * country[j].size();
}
}
long long temp =0;
for (int i = 0; c1>0 && i<country.size(); i++)
temp = temp + country[i].size();
if (c1> 0) result = result + (c1*(c1-1))/2 + temp*c1;
cout << result <<endl;
return 0;
}
https://www.hackerrank.com/challenges/journey-to-the-moon
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <ctime>
#include <cassert>
using namespace std;
int connected (int a, int b, vector<vector<int>> & v) {
queue<int> q;
vector<int> v1(v.size(), 0);
for (int i = 0; i< v[a].size(); i++) {
q.push(v[a][i]);
}
v1[a] = 1;
while(!q.empty()) {
if (q.front() == b) return 1;
if (v1[q.front()] == 0) {
for (int i = 0; i< v[q.front()].size(); i++) {
q.push(v[q.front()][i]);
}
}
v1[q.front()] = 1;
q.pop();
}
return 0;
}
int main()
{
int N, I;
int c = 0;
long long c1 = 0;
cin >> N >> I;
vector<vector<int> > pairs(N);
vector<vector<int> > country;
vector<int> v(N,0);
vector<int> v1(N,0);
for (int i = 0; i < I; ++i) {
int a, b;
cin >> a >> b;
pairs[a].push_back(b);
pairs[b].push_back(a);
}
long long result = 0;
/** Write code to compute the result using N,I,pairs **/
for (int i = 0; i < N; ++i) {
if (v[i] == 0 && pairs[i].size() > 0) {
vector<int> v2(0);
country.push_back(v2);
country[c].push_back(i);
v1[i] = 1;
for (int j = 0; j<pairs[i].size(); j++) {
if (v1[pairs[i][j]] == 0)
country[c].push_back(pairs[i][j]);
v1[pairs[i][j]] = 1;
}
v[i] = 1;
for(int k = 0; k<country[c].size(); k++) {
if (v[country[c][k]] == 0) {
for (int j = 0; j<pairs[country[c][k]].size(); j++) {
if (v1[pairs[country[c][k]][j]] == 0)
country[c].push_back(pairs[country[c][k]][j]);
v1[pairs[country[c][k]][j]] = 1;
}
}
v[country[c][k]] = 1;
}
c++;
//cout<<"here";
} else {
if (pairs[i].size() == 0) {
//vector<int> v2(0);
//country.push_back(v2);
//country[c].push_back(i);
c1++;
}
}
}
for (int i = 0; i<country.size(); i++) {
for (int j = i +1; j<country.size(); j++) {
result = result + country[i].size() * country[j].size();
}
}
long long temp =0;
for (int i = 0; c1>0 && i<country.size(); i++)
temp = temp + country[i].size();
if (c1> 0) result = result + (c1*(c1-1))/2 + temp*c1;
cout << result <<endl;
return 0;
}
Labels:
C/C++,
CODING,
Geeksforgeeks,
hackerrank,
Programming,
STL
List of all the websites a programmer or a codes or a techie must visit in his lifetime.
Blogs
- Coding Horror
- The Codist
- Martin Fowler
- Matt Might
- Me, Myself and Mathematics
- On Coding
- Peter Norvig
- Project Nayuki
- Stuff you need to Code Better!
Coding Style Guides
- CS 106B: Programming Abstractions
- Good C programming habits
- Google C++ Style Guide
- How to Report Bugs Effectively
- How do I debug my program?
General Advice and Tips
- Code Review Best Practices
- Dieter Rams | Ten Principles for Good Design
- How to become a programmer, or the art of Googling well
- Lessons From A Lifetime Of Being A Programmer
- Programming Isn't Manual Labor, But It Still Sucks
- Teach Yourself Programming in Ten Years
- Things I Wish Someone Had Told Me When I Was Learning How to Code
- What are some bad coding habits you would recommend a beginner avoid getting into?
- What every computer science major should know
Github
Interview Preparation
- Techie Delight
- CareerCup
- CSE Blog - quant, math, computer science puzzles
- Guide to Tech Interviews
- Here's How to Prepare for Tech Interviews
- How to Ace an Algorithms Interview
- LeetCode Online Judge
- Runhe Tian Coding Practice
- Tech Interview
News
Online Courses
- Hackr.io - Find & share the best online programming courses & tutorials
- Code School
- CodesDope
- CS 97SI: Introduction to Programming Contests
- Introduction to Algorithms
- Introduction to Computer Science and Programming
Programming Contests
Programming Practice
- CodeAbbey
- CodeKata
- Martyr2’s Mega Project List
- Mega Project List by Karan Goel
- Programming by Doing
- Programming Praxis
- Project Euler
- The Python Challenge
Reddit
- coding • /r/coding
- Computer Science: Theory and Application • /r/compsci
- CS Career Questions • /r/cscareerquestions
- For learning, refreshing, or just for fun! • /r/dailyprogrammer
- programming • /r/programming
- Reverse Engineering • /r/reverseengineering
Resources
Tutorials
- Bit Twiddling Hacks
- List of Problems - Techie Delight
- GeeksforGeeks
- Rosetta Code
- visualising data structures and algorithms through animation
Social Interaction
- DreamInCode.net
- Geeklist
- Programmers Stack Exchange
- Stack Overflow
- XDA-Developers Android Forums
- Codesdope : Discussion Forum
Wikipedia
Important interview Questions on C pointers
• C Pointers
o What does *p++ do? Does it increment p or the value pointed by p?
o What is a NULL pointer? How is it different from an unitialized pointer?
How is a NULL pointer defined?
o What is a null pointer assignment error?
o Does an array always get converted to a pointer? What is the difference
between arr and &arr? How does one declare a pointer to an entire array?
o Is the cast to malloc() required at all?
o What does malloc() , calloc(), realloc(), free() do? What are the common
problems with malloc()? Is there a way to find out how much memory a
pointer was allocated?
o What's the difference between const char *p, char * const p and const char
* const p?
o What is a void pointer? Why can't we perform arithmetic on a void *
pointer?
o What do Segmentation fault, access violation, core dump and Bus error
mean?
o What is the difference between an array of pointers and a pointer to an
array?
o What is a memory leak?
o What are brk() and sbrk() used for? How are they different from malloc()?
o What is a dangling pointer? What are reference counters with respect to
pointers?
o What do pointers contain?
o Is *(*(p+i)+j) is equivalent to p[i][j]? Is num[i] == i[num] == *(num + i)
== *(i + num)?
o What operations are valid on pointers? When does one get the Illegal use
of pointer in function error?
o What are near, far and huge pointers? New!
o What is the difference between malloc() and calloc()? New!
o Why is sizeof() an operator and not a function? New!
o What is an opaque pointer?
o What does *p++ do? Does it increment p or the value pointed by p?
o What is a NULL pointer? How is it different from an unitialized pointer?
How is a NULL pointer defined?
o What is a null pointer assignment error?
o Does an array always get converted to a pointer? What is the difference
between arr and &arr? How does one declare a pointer to an entire array?
o Is the cast to malloc() required at all?
o What does malloc() , calloc(), realloc(), free() do? What are the common
problems with malloc()? Is there a way to find out how much memory a
pointer was allocated?
o What's the difference between const char *p, char * const p and const char
* const p?
o What is a void pointer? Why can't we perform arithmetic on a void *
pointer?
o What do Segmentation fault, access violation, core dump and Bus error
mean?
o What is the difference between an array of pointers and a pointer to an
array?
o What is a memory leak?
o What are brk() and sbrk() used for? How are they different from malloc()?
o What is a dangling pointer? What are reference counters with respect to
pointers?
o What do pointers contain?
o Is *(*(p+i)+j) is equivalent to p[i][j]? Is num[i] == i[num] == *(num + i)
== *(i + num)?
o What operations are valid on pointers? When does one get the Illegal use
of pointer in function error?
o What are near, far and huge pointers? New!
o What is the difference between malloc() and calloc()? New!
o Why is sizeof() an operator and not a function? New!
o What is an opaque pointer?
Subscribe to:
Posts (Atom)