You are on page 1of 11

// CPP program for the above approach

#include <bits/stdc++.h>
using namespace std;
 
// A Dequeue (Double ended queue) based
// method for printing maximum element of
// all subarrays of size k
void printKMax(int arr[], int n, int k)
{
     
    // Create a Double Ended Queue,
    // Qi that will store indexes
    // of array elements
    // The queue will store indexes
    // of useful elements in every
    // window and it will
    // maintain decreasing order of
    // values from front to rear in Qi, i.e.,
    // arr[Qi.front[]] to arr[Qi.rear()]
    // are sorted in decreasing order
    std::deque<int> Qi(k);
 
    /* Process first k (or first window)
     elements of array */
    int i;
    for (i = 0; i < k; ++i)
    {
     
        // For every element, the previous
        // smaller elements are useless so
        // remove them from Qi
        while ((!Qi.empty()) && arr[i] >=
                            arr[Qi.back()])
           
             // Remove from rear
            Qi.pop_back();
 
        // Add new element at rear of queue
        Qi.push_back(i);
    }
 
    // Process rest of the elements,
    // i.e., from arr[k] to arr[n-1]
    for (; i < n; ++i)
    {
     
        // The element at the front of
        // the queue is the largest element of
        // previous window, so print it
        cout << arr[Qi.front()] << " ";
 
        // Remove the elements which
        // are out of this window
        while ((!Qi.empty()) && Qi.front() <=
                                           i - k)
           
            // Remove from front of queue
            Qi.pop_front();
 
        // Remove all elements
        // smaller than the currently
        // being added element (remove
        // useless elements)
        while ((!Qi.empty()) && arr[i] >=
                             arr[Qi.back()])
            Qi.pop_back();
 
        // Add current element at the rear of Qi
        Qi.push_back(i);
    }
 
    // Print the maximum element
    // of last window
    cout << arr[Qi.front()] << “\n”;
}
 
// Driver code
int main()
{
    int arr[] = { 12, 1, 78, 90, 57, 89, 56 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    printKMax(arr, n, k);
    return 0;
}

Problem

You inherited a piece of code that performs username validation for your company's website. The
existing function works reasonably well, but it throws an exception when the username is too short.
Upon review, you realize that nobody ever defined the exception. 

The inherited code is provided for you in the locked section of your editor. Complete the code so
that, when an exception is thrown, it prints Too short: n (where n is the length of the given
username).

Input Format :
The first line contains an integer, t, the number of test cases. 
Each of the t subsequent lines describes a test case as a single username string, n.
Constraints :
 1 <= t <= 1000
 1<= |u| <= 100
 The username consists only of uppercase and lowercase letters.

Output Format :
You are not responsible for directly printing anything to stdout. If your code is correct, the locked
stub code in your editor will print either Valid (if the username is valid), Invalid (if the username is
invalid), or Too short: n (where n is the length of the too-short username) on a new line for each test
case.

Sample Input :
3
Peter
Me
Arxwwz

Sample Output :
Valid
Too short: 2
Invalid

Explanation :
Username Me is too short because it only contains 2 characters, so your exception prints Too Short
: 2. 
All other validation is handled by the locked code in your editor. 

Solution :

1 //Inherited Code in C++ - Hacker Rank Solution


2 #include <iostream>
3 #include <string>
4 #include <sstream>
5 #include <exception>
6 using namespace std;
7
8 /* Define the exception here */
9 struct BadLengthException : exception
10 {
11 string s;
12 BadLengthException(int n) : s(to_string(n)) {}
13 const char *what() const noexcept override
14 {
15 return s.c_str();
16 }
17 };
18
19
20 bool checkUsername(string username)
21 {
22 bool isValid = true;
23 int n = username.length();
24 if(n < 5)
25 {
26 throw BadLengthException(n);
27 }
28 for(int i = 0; i < n-1; i++)
29 {
30 if(username[i] == 'w' && username[i+1] == 'w')
31 {
32 isValid = false;
33 }
34 }
35 return isValid;
36 }
37
38 int main()
39 {
40 int T; cin >> T;
41 while(T--)
42 {
43 string username;
44 cin >> username;
45 try
46 {
47 bool isValid = checkUsername(username);
48 if(isValid)
49 {
50 cout << "Valid" << '\n';
51 }
52 else
53 {
54 cout << "Invalid" << '\n';
55 }
56 }
57 catch (BadLengthException e)
58 {
59 cout << "Too short: " << e.what() << '\n';
60 }
61 }
62 return 0;
63 }

In this challenge, you are required to handle error messages while working with small computational server

that performs complex calculations.

It has a function that takes  large numbers as its input and returns a numeric result. Unfortunately, there are

various exceptions that may occur during execution.

Complete the code in your editor so that it prints appropriate error messages, should anything go wrong. The

expected behavior is defined as follows:

 If the compute function runs fine with the given arguments, then print the result of the function call.

 If it fails to allocate the memory that it needs, print Not enough memory.

 If any other standard C++ exception occurs, print Exception: S where  is the exception's error

message.

 If any non-standard exception occurs, print Other Exception.

Input Format

The first line contains an integer, , the number of test cases.

Each of the  subsequent lines describes a test case as  space-separated integers,  and , respectively.

Constraints

Output Format

For each test case, print a single line containing whichever message described in the Problem Statement above

is appropriate. After all messages have been printed, the locked stub code in your editor prints the server load.
Sample Input

2
-8 5
1435434255433 5
Sample Output

Exception: A is negative
Not enough memory
2
Explanation

 is negative, hence 'Exception: A is negative' is thrown. Since the second input is too large, 'not enough

memory' is displayed.  is the server load.

https://github.com/qianghaowork/Codecpp4/blob/master/ExceptionalServer.cpp

#include
<iostream
>
#include <exception>
#include <string>
#include <vector>
#include <cmath>
using namespace std;

class Server {
private:
static int load;
public:
static int compute(long long A, long long B) {
load += 1;
if(A < 0) {
throw std::invalid_argument("A is
negative");
}
vector<int> v(A, 0);
int real = -1, cmplx = sqrt(-1);
if(B == 0) throw 0;
real = (A/B)*real;
int ans = v.at(B);
return real + A - B*ans;
}
static int getLoad() {
return load;
}
};
int Server::load = 0;

int main() {
int T; cin >> T;
while(T--) {
long long A, B;
cin >> A >> B;
try {
int result = Server::compute(A,B);
cout << result << "\n";
}
catch(std::invalid_argument& e ){
cout << "Exception: A is negative\n";
}
catch(const std::bad_alloc& e){
cout << "Not enough memory\n";
}
catch(std::exception& e){
cout << "Exception: " << e.what() << "\n";
}
catch(...){
cout << "Other Exception\n";
}
}
cout << Server::getLoad() << endl;
return 0;
}

This problem is to get you familiar with virtual functions. Create three classes Person, Professor and Student.

The class Person should have data members name and age. The classes Professor and Student should inherit

from the class Person.


The class Professor should have two integer members: publications and cur_id. There will be two member

functions: getdata and putdata. The function getdata should get the input from the user: the name,

age and publications of the professor. The function putdata should print the name, age, publications and the

cur_id of the professor.

The class Student should have two data members: marks, which is an array of size  and cur_id. It has two

member functions: getdata and putdata. The function getdata should get the input from the user: the name,

age, and the marks of the student in  subjects. The function putdata should print the name, age, sum of the

marks and the cur_id of the student.

For each object being created of the Professor or the Student class, sequential id's should be assigned to them

starting from .

Solve this problem using virtual functions, constructors and static variables. You can create more data

members if you want.

Note: Expand the main function to look at how the input is being handled.

Input Format

The first line of input contains the number of objects that are being created. If the first line of input for each

object is , it means that the object being created is of the Professor class, you will have to input the name,

age and publications of the professor.

If the first line of input for each object is , it means that the object is of the Student class, you will have to input

the name, age and the marks of the student in  subjects.

Constraints

, where  is the length of the name.

, where marks is the marks of the student in each subject.

Output Format

There are two types of output depending on the object.


If the object is of type Professor, print the space separated name, age, publications and id on a new line.

If the object is of the Student class, print the space separated name, age, the sum of the marks in  subjects

and id on a new line.

Sample Input

4
1
Walter 56 99
2
Jesse 18 50 48 97 76 34 98
2
Pinkman 22 10 12 0 18 45 50
1
White 58 87
Sample Output

Walter 56 99 1
Jesse 18 403 1
Pinkman 22 135 2
White 58 87 2

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Person
{
    protected:
      int age;
      string name;
    public:
          virtual void getdata(){};
          virtual void putdata(){};
};
class Professor : public Person
{
    int publication;
    static int id1;
      public:
       void getdata()
       {
           cin>>name;
           cin>>age;
           cin>>publication;
       }
       void putdata()
       {
          cout<<name<<" "<<age<<" "<<publication<<" "<<id1<<endl;
          id1++;
       }
};
int Professor::id1=1;
class Student : public Person
{
    int marks[6];
     static int id2;
  public:
      int sum=0;
   void getdata()
   {
       cin>>name;
       cin>>age;
       for(int i=0;i<=5;i++)
       {
          cin>>marks[i];
          sum=sum+marks[i];
       }
   }
   void putdata()
   {
      cout<<name<<" "<<age<<" "<<sum<<" "<<id2<<endl;
      id2++;
   }
};

int Student::id2=1;

int main(){

    int n, val;
    cin>>n; //The number of objects that is going to be created.
    Person *per[n];

    for(int i = 0;i < n;i++){

        cin>>val;
        if(val == 1){
            // If val is 1 current object is of type Professor
            per[i] = new Professor;

        }
        else per[i] = new Student; // Else the current object is of type Student

        per[i]->getdata(); // Get the data from the user.

    }

    for(int i=0;i<n;i++)
        per[i]->putdata(); // Print the required output for each object.

    return 0;

You might also like