Wednesday, 28 February 2018

For Loop in STL C++

Different ways of writing for loop to loop through vectors in c++

vector<int> v;

for(int &t:v)
   cout<<t;

for(int i=0;i<v.size();i++)
     cout<<v[i];

vector<int>::iterator it;
for(it=v.begin();it != v.end();it++)
     cout<<*it;

Friday, 23 February 2018

Dictionaries and Maps Hacker Rank Solution in C/C++

https://www.hackerrank.com/challenges/linkedin-practice-dictionaries-and-maps/problem

C++ code that passes all test cases

#include <iostream>
#include <map>
using namespace std;

int main()
 {
map<string,long>pb;
int n;
string name;
cin>>n;
for(int i=0;i<n;i++)
{
        long num;
    cin>>name>>num;
    pb[name]=num;
}
while(cin>>name)
{
    if(pb[name])
            cout<<name<<"="<<pb[name]<<endl;
        else
            cout<<"Not found"<<endl;
}
}

C Code that passes only 2 test cases and timed out for other test cases:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
             
               int data;
               char name[1000];
               struct node *next;
};

int main()
{
        int n;
        scanf("%d",&n);
        struct node *head[26]={NULL},*c;
        for(int i=0;i<n;i++)
        {
            struct node * newnode=(struct node *)malloc(sizeof(struct node));
            int val;
            char temp[1000];
            scanf("%s%d",temp,&val);
            newnode->data=val; strcpy(newnode->name,temp);
               newnode->next = NULL;
               if(head[temp[0]-'a'] == NULL)
                    head[temp[0]-'a'] = newnode;
               else
               {
                    for(c=head[temp[0]-'a'];c->next != NULL;c=c->next);
                    c->next=newnode;
               }
         
        }
         for(int i=0;i<n;i++)
        {
            char temp[1000];int flag=1;
            scanf("%s",temp);
            if(head[temp[0]-'a'] == NULL)
                 printf("Not found\n");
            else
               {
                              for(c=head[temp[0]-'a'];c!=NULL;c=c->next)
                              {
                                  if(strcmp(temp,c->name) == 0)
                                  {
                                      printf("%s=%d\n",c->name,c->data);
                                      flag=0;break;
                                  }
                              }
                              if(flag)
                                printf("Not found\n");
                           
               }
        }
        return 0;
}


  

Sunday, 18 February 2018

Anagram Hacker Rank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int anagram(char* s){
    // Complete this function
    int l=strlen(s),c=0;
    if(l%2 != 0)
        return -1;
    int h1[26]={0},h2[26]={0},i;
    for(i=0;i<l/2;i++)
        h1[s[i]-'a']++;
    for(i=l/2;i<l;i++)
        h2[s[i]-'a']++;
    for(i=0;i<26;i++)
    {
        h1[i]=h1[i]-h2[i];
        if(h1[i]>0)
            c=c+abs(h1[i]);
      
    }
    return c;
}
int main() {
    int q;
    scanf("%i", &q);
    for(int a0 = 0; a0 < q; a0++){
        char* s = (char *)malloc(512000 * sizeof(char));
        scanf("%s", s);
        int result = anagram(s);
        printf("%d\n", result);
    }
    return 0;
}

Saturday, 17 February 2018

Smaller than the element code in c++

https://www.codechef.com/CODR2018/problems/KRYP6/


#include <stdio.h>
#include <iostream>
#include <set>

using namespace std;
set <long long> st;
set <long long>::iterator ind;
int main() {
    long long n,i=0;
    scanf("%lld",&n);
    long long *a=(long long *)malloc(sizeof(long long)*n);
    for(i=0;i<n;i++)
        scanf("%lld",&a[i]);
    for(i=0;i<n;i++)
    {
        ind = st.lower_bound(a[i]);
   
if (ind == st.begin())
    printf("-1\n");
else {
    ind--;
    printf("%lld\n", *ind);
}
st.insert(a[i]);
    }
 
return 0;
}

Tuesday, 6 February 2018

Climbing the Leaderboard Hacker Rank Solution in C

https://www.hackerrank.com/challenges/climbing-the-leaderboard/copy-from/61917526

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main() {
    int n,i,j,t,scores_i,k;
    scanf("%i", &n);
 
    int *scores = malloc(sizeof(int) * n);
    scanf("%i",&scores[0]);
    for (scores_i = 1,k=1; k < n;k++ )
    {
       scanf("%i",&t);
       if(t !=scores[scores_i-1])
       {
           scores[scores_i]=t; //scoring only distinct scores so that index gives the rank
           scores_i++;
       }
     }
    n=scores_i;
    int m,rank;
    j=n-1;//will store last index or the last rank
    scanf("%i", &m);
    int *alice = malloc(sizeof(int) * m);
    for (int alice_i = 0; alice_i < m; alice_i++) {
       scanf("%i",&alice[alice_i]);
    }
    for(i=0;i<m;i++)
    {
        while(j>=0 && alice[i]>scores[j])
            j--;
        if(j==-1)
            rank=1;
        else if(alice[i] == scores[j])
            rank=j+1;
        else if(alice[i] < scores[j])
            rank=j+2;
        printf("%d\n",rank);
    }
    return 0;
}

Minimum Absolute Difference in an Array, Marc's Cakewalk, Pairs, Minimum Loss Hacker Rank Solution in C

https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/copy-from/61462098

int co(const void *p, const void *q)
{
   return *(int *)p-*(int *)q;
}

int minimumAbsoluteDifference(int n, int arr_size, int* arr)
{
    int min,temp; 
    qsort(arr,n,sizeof(int),co);//to sort in ascending order
    min=abs(arr[0]-arr[1]);
    for(int i=1;i<n-1;i++)
    {
        int tmp=abs(arr[i]-arr[i+1]);
       if(min>tmp)
            min=tmp;
    }
    return min;
}

==============================================
https://www.hackerrank.com/challenges/marcs-cakewalk/problem

#include <math.h>
#include <stdio.h>

int co(const void *p, const void *q)
{
   return *(int *)q-*(int *)p;
}
int main(){
    int n,i;
    unsigned long int sum=0;
    scanf("%d",&n);
    int *calories = malloc(sizeof(int) * n);
    for(int calories_i = 0; calories_i < n; calories_i++){
       scanf("%d",&calories[calories_i]);
    }
    qsort(calories,n,sizeof(int),co);//sort in descending order
    for(i=0;i<n;i++)
        sum=sum+(calories[i]*pow(2,i));
             
    printf("%ld",sum);
    // your code goes here
    return 0;
}
=================================
https://www.hackerrank.com/challenges/pairs/copy-from/66162811
Pairs Hacker Rank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int co(const void *p, const void *q)
{
   return *(int *)p-*(int *)q;
}
int pairs(int k, int n, int* arr)
{
    int count =0,i=0;
    for(int j =1;j<n;)
    {
        int var=abs(arr[j]-arr[i]);
        if(var == k)
        {
            count++;
            j++;
        }
        else if(var>k)
            i++;
        else
            j++;
    }
    return count;
}

int main() {
    int n;
    int k;
    scanf("%i %i", &n, &k);
    int *arr = malloc(sizeof(int) * n);
    for (int arr_i = 0; arr_i < n; arr_i++) {
       scanf("%i",&arr[arr_i]);
    }
    qsort(arr,n,sizeof(int),co);
    int result = pairs(k, n, arr);
    printf("%d\n", result);
    return 0;
}
==================================================
https://www.codechef.com/CODR2018/problems/KRYP4
"The blood of House of El will always bind us together."
What the Kryptonians need is to be together, to be united in order to save the apocalypse.
For that, Seg-El has decided to carry out some encoding. The people of the same behavior if made to stay together will lead to enhanced protection of Krypton.
There are N people on Krypton. Each has a behavior A[i] associated with him/her.
You need to tell Seg-El the total number of ways to choose any two people of same behavior so that they can be made to stay together.

Input

First line consists of N - the number of people.
Second line comprises N space separated integers denoting A[i].

Output

Print the answer to the number of ways to place 2 people together having same behaviour.

Constraints

  • 1 ≤ N ≤ 100000
  • 1 ≤ A[i] ≤ 1015

Example

Input:
4
1 1 2 2
Output:
 2

Explanation

There is only 1 way in which 2 people with behavior 1 can be together. Similarly, for behavior 2 people. Hence, total number of ways are 2.

Solution:
#include<stdio.h>
int cmpfunc (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}
int main()
{
    long long t;
    scanf("%lld",&t);
    long long a[t];
    for(long long i=0;i<t;i++)
    {
        scanf("%lld",&a[i]);
    }
    qsort(a,t,sizeof(long long),cmpfunc);
    long long count=0;
    long long sum=0;
    long long temp=a[0];
    for(long long i=0;i<t;i++)
    {
        if(temp==a[i])
        count++;
        else
        {
            temp=a[i];
            if(count>=2)
                  sum+=(count*(count-1)/2);
            count=1;
        }
    }
    if(count>=2)
    {
        sum+=(count*(count-1)/2);
    }
    printf("%lld\n",sum);
}
 
================================
 problem : https://www.hackerrank.com/challenges/minimum-loss/
 
Solution:
 
struct h
{
    long int hp,in;
};
int co(const void *p, const void *q)
{
    struct h *x = (struct h *) p;
    struct h *y = (struct h *) q;
    if (x->hp < y->hp)
        return -1;
    else if (x->hp > y->hp)
        return 1;
    return 0;
}//ascending order sorting

long int minimumLoss(int n, long* price) {
long int i,j,min=LONG_MAX,diff;
    struct h h1[n];
    for(i=0;i<n;i++)
    {
        h1[i].hp=price[i];
        h1[i].in=i;
    }
    qsort(h1,n,sizeof(struct h),co);
    for(i=0;i<n-1;i++)
    {
        diff=h1[i+1].hp - h1[i].hp;
        if(min>diff &&(h1[i+1].in < h1[i].in))
            min=diff;
    }
return min;
} 

Monday, 5 February 2018

Separate the Numbers Hacker Rank Solution in C

https://www.hackerrank.com/challenges/separate-the-numbers/problem

Copied from discussion -- code written in c++ by Mohit_MR
Uses the concept of backtracking

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

void separateNumbers(char* s) {
    // Complete this function
    long int d1=0,d2=0,d3,l=strlen(s),f;
    for(long int i=0;i<=l/2;i++)
    {
        d1=d1*10+(int)(s[i]-'0');
        d3=d1;
        d2=0;
        f=0;
        for(long int j = i+1;j<l;j++)
        {
            d2=d2*10+(int)(s[j]-'0');// second digit
            if(d2 == 0 || (d2-d1)>1)
            {
                f=0;
                break;
            }
            if(d2-d1 == 1)
            {
                f=1;
                d1=d2;
                d2=0;
            }
            else
                f=0;
        }
        if(f)
        {
            printf("YES %ld\n",d3);
            break;
        }
         
        d1=d3;
    }
    if(f == 0)
        printf("NO\n");
}

int main() {
    int q;
    scanf("%i", &q);
    for(int a0 = 0; a0 < q; a0++){
        char* s = (char *)malloc(512000 * sizeof(char));
        scanf("%s", s);
        separateNumbers(s);
    }
    return 0;
}

Counting Valleys Hacker Rank Solution in C

https://www.hackerrank.com/challenges/counting-valleys/problem

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int countingValleys(int n, char* s) {
    // Complete this function
      int c=0,v=0;
    for(int i=0;s[i] !='\0';i++)
    {
        if(s[i] == 'D')
            c--;
        else if(s[i] == 'U')
        {
            c++;
            if(c == 0 && s[i] == 'U')
                v++;
        }
           
    }
    return v;
}

int main() {
    int n;
    scanf("%i", &n);
    char* s = (char *)malloc(1000000 * sizeof(char));
    scanf("%s", s);
    int result = countingValleys(n, s);
    printf("%d\n", result);
    return 0;
}

Friday, 2 February 2018

Recursion-14 hacker rank solution in C

https://www.hackerrank.com/contests/elite-recursion/challenges/recursion-14/problem


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int n,k,t;
void rpat()
{
   if(n == t)
       return;
    
    printf("%d ",n);
    n=n+k;
    rpat();
}
void fpat()
{
    if(n<=0)
    {
        rpat();
        return;
    }
        
    printf("%d ",n);
    n=n-k;
    fpat();
}

int main() {
    scanf("%d%d",&n,&k);
    t=n;
    fpat();
    printf("%d ",n);
    return 0;
}

Thursday, 1 February 2018

Beautiful Triplets , Equalize the Array, Sock Merchant Hacker Rank Solution in C/c++ ,Weapon value code chef solution in c

Beautiful Triplets

here a[j]-a[i] must be equal to d and 
a[k]-[j] = d

so solving a[j]-a[i] =d we get a[i] = a[j] -d

and solving a[k]-a[j] =d we get a[k] = a[j] + d
so according to problem statement a[j]-d and a[j] +d must be in the array...

but if we write the if condition as h[a[i]-d] >=1 and h[a[i]+d >=1 then this logic will fail wen there are repetitions
Example:
  • 10 3
  • 1 6 7 7 8 10 12 13 14 19


here 10-3 = 7 and 7 exists in array
10+3 is 13 and 13 also exists in array but the if condition will only count once

but since there is another 7, another beautiful triplet (7,10,13) also exists.

No we must change the if condition
a[j]-d, a[j] and a[j]+d must be in array
it is as good as

a[i], a[i]+d, a[i]+2d must exist in array (since a[i] = a[j]-d)

so our for loop would be
h[a[i]+d] >=1 and h[a[i]+2*d] >=1

Solution:

#include <stdio.h>

int main() 
{
    int n,d; 
    scanf("%d%d", &n,&d);
    long long int a[n],h[2000001]={0},c=0,i;
    for (i = 0; i < n; i++)
    {
       scanf("%lld",&a[i]);
        h[a[i]]++;
    }
    for( i=0;i<n;i++)
        if( h[a[i]+d] >=1 && h[a[i]+2*d]>=1)
            c++;
    printf("%lld\n", c);
}


Equalize the Array

https://www.hackerrank.com/challenges/equality-in-a-array/problem

#include <stdio.h>
int main()
{
    int n,h[101]={0};
    scanf("%d", &n);
    int a[n],max=0,c=0;
    for(int i=0;i<n;i++)
    {
        scanf("%d", &a[i]);
        h[a[i]]++;
        if(h[a[i]]>max)
            max=h[a[i]];
    }
    printf("%d",n-max);
}

Sock Merchant

https://www.hackerrank.com/challenges/sock-merchant/copy-from/62004605

In C :

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main() {
    int n,i,s=0;
    scanf("%i", &n);
    int *ar = malloc(sizeof(int) * n);
    int b[101]={0};
    for(int ar_i = 0; ar_i < n; ar_i++){
       scanf("%i",&ar[ar_i]);
        b[ar[ar_i]]++;
    }
    for(i=0;i<101;i++)
        s=s+b[i]/2;
    printf("%d\n", s);
    return 0;
}

In C++

int main() {
    map<int,int> socks;
    int i, total=0;
    cin.ignore();
    while(cin>>i){
       socks[i]++;
       if(!(socks[i]%2))
           total++;
    }
    cout<<total;
    return 0;
}

In Java

static int sockMerchant(int n , int ar[])
{
         Map<Integer, Integer> map = new HashMap();
         int ans=0;
         for(int val: ar)
         {
               Integer c = map.get(val);
               if(c == null)
                      map.put(val,1);
               else
                      map.put(val,c+1);
          }
          for(int z: map.values())
                    ans=ans+z/2;
          return ans;
}
========================================================================
https://www.hackerrank.com/challenges/beautiful-triplets/problem

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int h[20001]={0};
int beautifulTriplets(int d, int arr_size, int* arr) {
    // Complete this function
    int c=0;
    for(int i=1;i<arr_size;i++)
        if(h[arr[i]-d] ==1 && h[arr[i]+d]==1)
            c++;
    return c;
}

int main() {
    int n;
    int d;
    scanf("%i %i", &n, &d);
    int *arr = malloc(sizeof(int) * n);
    for (int arr_i = 0; arr_i < n; arr_i++) {
       scanf("%i",&arr[arr_i]);
        h[arr[arr_i]]++;
    }
    int result = beautifulTriplets(d, n, arr);
    printf("%d\n", result);
    return 0;
}
========================================================================


Weapon Value CodeChef solution 
#include<stdio.h>

int main() {
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,i,j,c=0;
        scanf("%d",&n);
        char st[n][11];
        int h[26]={0};
        for(i=0;i<n;i++)
            scanf("%s",&st[i]);
        for(i=0;i<n;i++)
        {
            for(j=0;st[i][j]!='\0';j++)
            {
                if(st[i][j] == '1')
                    h[j]++;
            }
        }
        for(i=0;i<11;i++)
            if(h[i] !=0 && h[i]%2 == 1)
                c++;
        printf("%d\n",c);
    }
}

Other Wonderful problems on hashing

Sherlock and Squares Hacker Rank Solution in C

https://www.hackerrank.com/challenges/sherlock-and-squares/problem


#include <stdio.h>
#include <math.h>
int main() 
{
    int q; 
    scanf("%d", &q);
    while(q--)
    {
        int a,b,c=0
        scanf("%d%d", &a, &b);
        for(int i=sqrt(a);i<=sqrt(b);i++)
        {
            int k=i*i;
            if(k>=a && k<=b)
                c++;
        }
        printf("%d\n", c);
    }
    return 0;
}