HackerRank 30 Days of Code solutions
Day 0: Hello, World
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string input_string;
getline(cin, input_string);
cout << "Hello, World." << endl << input_string << endl;
return 0;
}
Day 1: Data Types
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
return 0;
}
Day 2: Operators
#include <cmath>
#include <iostream>
using namespace std;
int main() {
string tmp;
getline(cin, tmp);
double mealCost = stod(tmp);
getline(cin, tmp);
int tipPercent = stoi(tmp);
getline(cin, tmp);
int taxPercent = stoi(tmp);
double tip = tipPercent * mealCost / 100;
double tax = taxPercent * mealCost / 100;
int totalCost = (int) round(tip + tax + mealCost);
cout<<totalCost;
return 0;
}
Day 3: Intro to Conditional Statements
//conditional statements
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
if (n%2 == 0)
{
// cout << "Weird"<<endl;
if (n>2 && n<5)
{
cout << "Not Weird"<<endl;
}
else if (n>6 && n<20)
{
cout << "Weird"<<endl;
}
else if (n>20)
{
cout << "Not Weird"<<endl;
}
else{
cout << "Weird"<< endl;
}
}
if (n%2 != 0)
{
cout << "Weird"<<endl;
}
return 0;
}
Day 4: Class vs. Instance
using namespace std;
#include <iostream>
class Person{
public:
int age;
Person(int initialAge);
void amIOld();
void yearPasses();
};
Person::Person(int initialAge){
if (initialAge > 0)
{
age = initialAge;
}
else{
cout << "Age is not valid, setting age to 0." << endl;
age = 0;
}
}
void Person::amIOld(){
if (age < 13)
{
cout << "You are young." << endl;
}
else if (age >= 13 && age < 18)
{
cout << "You are a teenager." << endl;
}
else{
cout << "You are old." << endl;
}
}
void Person::yearPasses(){
age+=1;
}
int main(){
int t;
int age;
cin >> t;
for(int i=0; i < t; i++) {
cin >> age;
Person p(age);
p.amIOld();
for(int j=0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
cout << '\n';
}
return 0;
}
Day 5: Loops
// loops
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
for (int i = 1; i <= 10; i++)
{
cout << n << " x " << i << " = " << n*i << endl;
}
return 0;
}
Day 6: Let's Review
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int T;
string S, evens, odds;
int N;
cin >> T;
while (T > 0) {
cin >> S;
N = S.length();
for (int i = 0; i < N; i++)
{
if (i % 2 == 0)
{
evens += S[i];
}
else {
odds += S[i];
}
}
cout << evens + " " + odds << endl;
evens = odds = "";
T--;
}
return 0;
}
Day 7: Arrays
#include <iostream>
using namespace std;
void reverseArray(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start ++;
end--;
}
}
void printReArray(int arr[], int size) {
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
}
int main() {
int N;
cin >> N;
int arr[N];
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
reverseArray(arr, 0, N - 1);
printReArray(arr, N);
return 0;
}
Day 8: Dictionaries and Maps
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
int n;
string name, phone;
string query;
std::map<string, string> phonebook;
cin >> n;
// insert contacts into phonebook
while (n > 0) {
cin >> name;
cin >> phone;
phonebook.insert({name, phone});
n--;
}
// querying contact from phonebook
map<std::string, std::string> :: iterator itr;
while (cin >> query && query.length()) {
itr = phonebook.find(query);
if (itr != phonebook.end())
{
cout << itr->first << "=" << itr->second << endl;
}
else {
cout << "Not found" << endl;
}
}
return 0;
}
Day 9: Recursion 3
#include <iostream>
using namespace std;
int factorial(int n) {
if (n > 1)
return n * factorial(n - 1);
return 1;
}
int main() {
int n, fact;
cin >> n;
fact = factorial(n);
cout << fact << endl;
return 0;
}
Day 10: Binary Numbers
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int maxConsecutiveOnes(int n) {
int count = 0;
while (n != 0) {
n = (n & (n << 1));
count++;
}
return count;
}
int main() {
int n;
cin >> n;
cout << maxConsecutiveOnes(n) << endl;
return 0;
}
Day 11: 2D Arrays
#include <iostream>
#include <math.h>
using namespace std;
const int row = 6;
const int col = 6;
int max_sum = 0;
int asn = 0;
int hourglass_sum;
int get_max_hourglass(int mat[row][col]) {
// hourglass
for (int i = 0; i < row - 2; i++)
{
for (int j = 0; j < col - 2; j++)
{
hourglass_sum = (mat[i][j] + mat[i][j + 1] + mat[i][j + 2]) +
(mat[i + 1][j + 1]) +
(mat[i + 2][j] + mat[i + 2][j + 1] + mat[i + 2][j + 2]);
if (asn == 0)
{
max_sum = hourglass_sum;
asn++;
}
max_sum = max(max_sum, hourglass_sum);
}
}
return max_sum;
}
int main() {
int mat[row][col];
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
cin >> mat[i][j];
}
}
cout << get_max_hourglass(mat) << endl;
return 0;
}
Day 12: Inheritance
#include <iostream>
#include <vector>
using namespace std;
class Person{
protected:
string firstName;
string lastName;
int id;
public:
Person(string firstName, string lastName, int identification){
this->firstName = firstName;
this->lastName = lastName;
this->id = identification;
}
void printPerson(){
cout<< "Name: "<< lastName << ", "<< firstName <<"\nID: "<< id << "\n";
}
};
class Student : public Person{
private:
vector<int> testScores;
public:
// Write your constructor here
Student(string firstName, string lastName, int id, vector<int>& scores) : Person(firstName,lastName,id), testScores(scores){
this->testScores = scores;
}
char calculate() { int avg=0;
for (int i = 0; i < testScores.size(); ++i)
{
avg += testScores[i];
}
avg = avg / testScores.size();
return (avg >= 90 ? 'O' : avg >= 80 ? 'E' : avg >= 70 ? 'A' : avg >= 55 ? 'P' : avg >= 40 ? 'D' : 'T');
}
};
int main() {
string firstName;
string lastName;
int id;
int numScores;
cin >> firstName >> lastName >> id >> numScores;
vector<int> scores;
for(int i = 0; i < numScores; i++){
int tmpScore;
cin >> tmpScore;
scores.push_back(tmpScore);
}
Student* s = new Student(firstName, lastName, id, scores);
s->printPerson();
cout << "Grade: " << s->calculate() << "\n";
return 0;
}
Day 13: Abstract Classes
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Book{
protected:
string title;
string author;
public:
Book(string t,string a){
title=t;
author=a;
}
virtual void display()=0;
};
class MyBook : Book {public:
int price;
MyBook(string t, string a, int p): Book(t, a) {
this->price = p;
}
void display() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Price: " << price << endl;
}
};
int main() {
string title,author;
int price;
getline(cin,title);
getline(cin,author);
cin>>price;
MyBook novel(title,author,price);
novel.display();
return 0;
}
Day 14: Scope
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Difference {
private:
vector<int> elements;
public:
int maximumDifference;
Difference(vector<int> a) {
this->elements = a;
}
void computeDifference() {
int min = *min_element(elements.begin(), elements.end());
int max = *max_element(elements.begin(), elements.end());
this->maximumDifference = max - min;
}
}; // End of Difference class
int main() {
int N;
cin >> N;
vector<int> a;
for (int i = 0; i < N; i++) {
int e;
cin >> e;
a.push_back(e);
}
Difference d(a);
d.computeDifference();
cout << d.maximumDifference;
return 0;
}
Day 15: Linked List
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* insert(Node *head,int data)
{
//Complete this method
if (head == NULL)
head = new Node(data);
else {
Node *curr = head;
while (curr->next)
curr = curr->next;
curr->next = new Node(data);
}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
mylist.display(head);
}
Day 16: Exceptions - String to Integer
#include <bits/stdc++.h>
using namespace std;
int main()
{
string S;
getline(cin, S);
try {
int num = stoi(S);
cout << num << endl;
}
catch (exception e) {
cout << "Bad String" << endl;
}
return 0;
}
Day 17: More Exceptions
#include <cmath>
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
//Write your code here
class Calculator {
public:
int power(int n, int p) {
if (n < 0 || p < 0)
{
throw invalid_argument("n and p should be non-negative");
}
int power = 1;
for (int i = 0; i < p; ++i)
{
power *= n;
}
return power;
}
};
int main()
{
Calculator myCalculator=Calculator();
int T,n,p;
cin>>T;
while(T-->0){
if(scanf("%d %d",&n,&p)==2){
try{
int ans=myCalculator.power(n,p);
cout<<ans<<endl;
}
catch(exception& e){
cout<<e.what()<<endl;
}
}
}
}
Day 18: Queues and Stacks
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
class Solution {
private:
queue<char> q;
stack<char> s;
public:
char popCharacter() {
char tmp = s.top();
s.pop();
return tmp;
}
void pushCharacter(char ch) {
s.push(ch);
}
char dequeueCharacter() {
char tmp = q.front();
q.pop();
return tmp;
}
void enqueueCharacter(char ch) {
q.push(ch);
}
};
int main() {
// read the string s.
string s;
getline(cin, s);
// create the Solution class object p.
Solution obj;
// push/enqueue all the characters of string s to stack.
for (int i = 0; i < s.length(); i++) {
obj.pushCharacter(s[i]);
obj.enqueueCharacter(s[i]);
}
bool isPalindrome = true;
// pop the top character from stack.
// dequeue the first character from queue.
// compare both the characters.
for (int i = 0; i < s.length() / 2; i++) {
if (obj.popCharacter() != obj.dequeueCharacter()) {
isPalindrome = false;
break;
}
}
// finally print whether string s is palindrome or not.
if (isPalindrome) {
cout << "The word, " << s << ", is a palindrome.";
} else {
cout << "The word, " << s << ", is not a palindrome.";
}
return 0;
}
Day 19: Interfaces
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class AdvancedArithmetic{
public:
virtual int divisorSum(int n)=0;
};
class Calculator : public AdvancedArithmetic {
public:
int divisorSum(int n) {
int sum = 0;
for (int i = 1; i <= n; ++i)
if (n % i == 0) sum += i;
return sum;
}
};
int main(){
int n;
cin >> n;
AdvancedArithmetic *myCalculator = new Calculator();
int sum = myCalculator->divisorSum(n);
cout << "I implemented: AdvancedArithmetic\n" << sum;
return 0;
}
Day 20: Sorting
// sortig
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int numSwaps = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
numSwaps++;
}
}
if (numSwaps == 0) break;
}
printf("Array is sorted in %i swaps.\n", numSwaps);
printf("First Element: %i\n", arr[0]);
printf("Last Element: %i\n", arr[arr.size() - 1]);
return 0;
}
Day 21: Generics
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template<typename T>
void printArray(vector<T> arr) {
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << endl;
}
int main() {
int n;
cin >> n;
vector<int> int_vector(n);
for (int i = 0; i < n; i++) {
int value;
cin >> value;
int_vector[i] = value;
}
cin >> n;
vector<string> string_vector(n);
for (int i = 0; i < n; i++) {
string value;
cin >> value;
string_vector[i] = value;
}
printArray<int>(int_vector);
printArray<string>(string_vector);
return 0;
}
Day 22: Binary Search Trees
#include <iostream>
#include <cstddef>
using namespace std;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int d){
data = d;
left = NULL;
right = NULL;
}
};
class Solution{
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
}
else {
Node* cur;
if(data <= root->data){
cur = insert(root->left, data);
root->left = cur;
}
else{
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}
int getHeight(Node* root){
//Write your code here
return root == NULL ? -1 : 1 + max(getHeight(root->left), getHeight(root->right));
}
}; //End of Solution
int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
cin >> t;
while(t-- > 0){
cin >> data;
root = myTree.insert(root, data);
}
int height = myTree.getHeight(root);
cout << height;
return 0;
}
Day 23: BST Level-Order Traversal
#include <iostream>
#include <cstddef>
#include <queue>
#include <string>
#include <cstdlib>
using namespace std;
class Node{
public:
int data;
Node *left,*right;
Node(int d){
data=d;
left=right=NULL;
}
};
class Solution{
public:
Node* insert(Node* root, int data){
if(root==NULL){
return new Node(data);
}
else{
Node* cur;
if(data<=root->data){
cur=insert(root->left,data);
root->left=cur;
}
else{
cur=insert(root->right,data);
root->right=cur;
}
return root;
}
}
void levelOrder(Node * root){
//Write your code here
queue<Node *> q;
q.push(root);
while (q.size() != 0) {
Node *curr = q.front();
q.pop();
cout << curr->data << " ";
if (curr->left) {
q.push(curr->left);
}
if (curr->right) {
q.push(curr->right);
}
}
}
};//End of Solution
int main(){
Solution myTree;
Node* root=NULL;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
root= myTree.insert(root,data);
}
myTree.levelOrder(root);
return 0;
}
Day 24: More Linked Lists
#include <cstddef>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* removeDuplicates(Node *head)
{
//Write your code here
Node *curr = head;
while (curr && curr->next) {
while (curr->next && curr->data == curr->next->data) {
curr->next = curr->next->next;
}
curr = curr->next;
}
return head;
}
Node* insert(Node *head,int data)
{
Node* p=new Node(data);
if(head==NULL){
head=p;
}
else if(head->next==NULL){
head->next=p;
}
else{
Node *start=head;
while(start->next!=NULL){
start=start->next;
}
start->next=p;
}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
head=mylist.removeDuplicates(head);
mylist.display(head);
}
Day 25: Running Time and Complexity
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool isPrime(int n) {
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0) return false;
return true;
}
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
int n;
cin >> n;
if (n >= 2 && isPrime(n)) {
cout << "Prime" << endl;
}
else {
cout << "Not prime" << endl;
}
}
return 0;
}
Day 26: Nested Logic
// Nested Logic
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int d_actual, m_actual, y_actual;
cin >> d_actual;
cin >> m_actual;
cin >> y_actual;
int d_expected, m_expected, y_expected;
cin >> d_expected;
cin >> m_expected;
cin >> y_expected;
int fine = 0;
if (y_actual > y_expected) fine = 10000;
else if (y_actual == y_expected) {
if (m_actual > m_expected) fine = (m_actual - m_expected) * 500;
else if (m_actual == m_expected && d_actual > d_expected) fine = (d_actual - d_expected) * 15;
}
cout << fine;
return 0;
}
Day 27: Testing
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cassert>
#include <set>
using namespace std;
int minimum_index(vector<int> seq) {
if (seq.empty()) {
throw invalid_argument("Cannot get the minimum value index from an empty sequence");
}
int min_idx = 0;
for (int i = 1; i < seq.size(); ++i) {
if (seq[i] < seq[min_idx]) {
min_idx = i;
}
}
return min_idx;
}
class TestDataEmptyArray {
public:
static vector<int> get_array() {
vector<int> vect{};
return vect;
}
};
class TestDataUniqueValues {
public:
static vector<int> get_array() {
vector<int> vect{ 23,5,8,12,7 };
return vect;
}
static int get_expected_result() {
return 1;
}
};
class TestDataExactlyTwoDifferentMinimums {
public:
static vector<int> get_array() {
vector<int> vect{ 9,23,3,8,12,3,7 };
return vect;
}
static int get_expected_result() {
return 2;
}
};
void TestWithEmptyArray() {
try {
auto seq = TestDataEmptyArray::get_array();
auto result = minimum_index(seq);
} catch (invalid_argument& e) {
return;
}
assert(false);
}
void TestWithUniqueValues() {
auto seq = TestDataUniqueValues::get_array();
assert(seq.size() >= 2);
assert(set<int>(seq.begin(), seq.end()).size() == seq.size());
auto expected_result = TestDataUniqueValues::get_expected_result();
auto result = minimum_index(seq);
assert(result == expected_result);
}
void TestWithExactlyTwoDifferentMinimums() {
auto seq = TestDataExactlyTwoDifferentMinimums::get_array();
assert(seq.size() >= 2);
auto tmp = seq;
sort(tmp.begin(), tmp.end());
assert(tmp[0] == tmp[1] and (tmp.size() == 2 or tmp[1] < tmp[2]));
auto expected_result = TestDataExactlyTwoDifferentMinimums::get_expected_result();
auto result = minimum_index(seq);
assert(result == expected_result);
}
int main() {
TestWithEmptyArray();
TestWithUniqueValues();
TestWithExactlyTwoDifferentMinimums();
cout << "OK" << endl;
return 0;
}
Day 28: RegEx, Patterns, and Intro to Databases
#include <bits/stdc++.h>
using namespace std;
int main()
{
int N;
cin >> N;
vector<string> emails(N);
vector<string> names(N);
vector<string> gmailUsers;
for(int i = 0; i < N; i++)
{
cin >> names[i] >> emails[i];
}
for(int i = 0; i < N; i++)
{
if(regex_match(emails[i], regex("(.*)@gmail.com")))
gmailUsers.push_back(names[i]);
}
sort(gmailUsers.begin(), gmailUsers.end());
for(int index = 0; index < gmailUsers.size(); index++)
{
cout << gmailUsers[index] << endl;
}
return 0;
}
Day 29: Bitwise AND
// BitWise in CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
int N, K;
for (int i = 0; i < t; i++)
{
vector<int> s;
cin >> N >> K;
for (int j = 1; j <= N; j++)
{
s.push_back(j);
}
int maximum = 0;
for (int A = 0; A < N; A++)
{
for (int B = A + 1; B < N; B++)
{
if ((s[A] & s[B]) < K && (s[A] & s[B]) > maximum)
maximum = (s[A] & s[B]);
}
}
cout << maximum << endl;
}
return 0;
}
Post a Comment