Monday, 9 March 2015

Hackerrank Pangrams Solution

Problem Statement
Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly because it is a pangram. ( pangrams are sentences constructed by using every letter of the alphabet at least once. )
After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.
Given a sentence s, tell Roy if it is a pangram or not.

(Explanation for the code is available in the first comment)


Source Code:
 #include <cmath>  
 #include <cstdio>  
 #include <vector>  
 #include <iostream>  
 #include <algorithm>  
 #include <stdio.h>  
 using namespace std;  
 int main() {  
   /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
   char arr[10000];  
   gets(arr);  
   int a[150]={0};  
   for(int i =0;arr[i]!='\0';i++){  
     char t;  
     t = tolower(arr[i]);  
     int n = t;  
     if(n>0)  
     {  
       a[n]++;  
       //cout<<n<<endl;  
     }  
   }  
   int flag = 1;  
   for(int i = 97;i<123;i++){  
     if(a[i]==0){  
       flag = 0;  
     }  
   }  
   if(flag == 1)  
     cout<<"pangram"<<endl;  
   else  
     cout<<"not pangram"<<endl;  
   return 0;  
 }  
** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

3 comments:

  1. Hi! Can you pls explain the given code?Thanks! :)

    ReplyDelete
    Replies

    1. char arr[10000];
      gets(arr); // reads input

      int a[150]={0}; //array used as a hashtable with initializing to 0.
      for(int i =0;arr[i]!='\0';i++){ // loop until the end of the input string
      char t;
      t = tolower(arr[i]); //convert the character to lowercase (since it is case insensitive)
      int n = t;
      if(n>0)
      {
      a[n]++; //store the count of the occurrence of a character

      }
      }
      int flag = 1;
      for(int i = 97;i<123;i++){ //check all the values of hashtable
      if(a[i]==0){ //if there is any missing character set flag as 0
      flag = 0;
      }
      }
      if(flag == 1) //print panagram if all the characters are present in the given string :)
      cout<<"pangram"<<endl;
      else
      cout<<"not pangram"<<endl;
      return 0;
      }

      Delete
    2. hope this helps :) :)

      Delete