HackerRank Algorithms Solutions using Python and C++(CPP)
Tags: cpp, python, computerscience, algorithms
Published: 2020-07-29 14:20:08

This page is moved to [codeperfectplus](https://codeperfectplus.com/hackerrank-algorithms-solutions-using-python-and-c-cpp). Please checkout for latest code.
Check out the [link here](https://codeperfectplus.com/hackerrank-algorithms-solutions-using-python-and-c-cpp)

### **what is algorithms**

An algorithm is a set of instructions that are used to accomplish a task, such as finding the largest number in a list, removing all the red cards from a deck of playing cards, sorting a collection of names, figuring out an average movie rating from just your friend's opinion

It's an essential part of programming. It comes under the fundamentals of computer science. It gives us the advantage of writing better and efficient code in less time. It is a key topic when it comes to Software Engineering interview questions so as developers, we must have knowledge of Algorithms

![HackerRank Algorithms Solution using python and cpp(c++)](https://dev-to-uploads.s3.amazonaws.com/i/swpx5z2kbro2sw4jq0df.jpg)

### **what's HackerRank**

HackerRank is a place where programmers from all over the world come together to solve problems in a wide range of Computer Science domains such as algorithms, machine learning, or artificial intelligence, as well as to practice different programming paradigms like functional programming.

### **Solution to Algorithms HackerRank solution**

HackerRank Algorithms Solution using Python & C++

{% github https://github.com/codePerfectPlus/competitive-programming-solution no-readme %}

## **Problems**

## [Solve Me First - HackerRank solution in Python and C++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Problem Statement: the sum of the above two integers

```cpp
int solveMeFirst(int a, int b) {
 // Hint: Type return a+b; below:
  return a + b;
}
```
```python
def solveMeFirst(a:int,b:int):
	# Hint: Type return a+b below
    return a + b
```
## [Simple Array Sum - HackerRank solution in Python and c++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Problem Statement: Print the sum of the array's elements as a single integer.

```cpp
int simpleArraySum(vector<int> ar) {
    /*
     * Write your code here.
     */
    return accumulate(ar.begin(), ar.end(), 0);
}
```

```python
def simpleArraySum(ar:list):
    return(sum(ar))
```
## [Compare the Triplets - HackerRank solution in Python and c++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Problem Statement: Complete the function compareTriplets in the editor below. It must return an array of two integers, the first being Alice's score and the second being Bob's.

compareTriplets has the following parameter(s):

- a: an array of integers representing Alice's challenge rating
- b: an array of integers representing Bob's challenge rating

```cpp
vector<int> compareTriplets(vector<int> a, vector<int> b) {
    
    vector<int> result;
    int aliceScore = 0;
    int bobScore = 0;

    for(int i=0;i<a.size();i++){
        if(a[i] > b[i]) 
            aliceScore ++;
        else if(b[i] > a[i])
            bobScore++;
        }         
        result.push_back(aliceScore);
        result.push_back(bobScore);
        return result;
}
```

```python
def compareTriplets(a:list, b:list):
    aliceScore = 0
    bobScore = 0
    for i in range(len(a)):     
        if a[i] > b[i]:
            aliceScore += 1
        elif b[i] > a[i]:
            bobScore += 1
    return [aliceScore,bobScore]
```

## [A very big sum - HackerRank solution in Python and c++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Problem Statement : 
        Complete the aVeryBigSum function in the editor below. It must return the sum of all array elements. aVeryBigSum has the following parameter(s):

- ar: an array of integers.

```cpp
long aVeryBigSum(vector<long> ar) {
    
    long long int total =  accumulate(ar.begin(), ar.end(), 0ll);
    return total;
}
```

```python
def aVeryBigSum(ar):
    return sum(ar)
```

## [Diagonal difference - HackerRank solution in Python and c++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Problem Statement: Given a square matrix, calculate the absolute difference between the sums of its diagonals.

```cpp
int diagonalDifference(vector<vector<int>> arr) {

    int s1 = 0;
    int s2 = 0;
    int n = arr.size();
    
    for(int i=0;i<n;i++) {        
        s1 += arr[i][i];
        s2 += arr[i][n-i-1];
    }
    return abs(s1 - s2); 
}
```

```python
def diagonalDifference(arr):
    # Write your code here
    d1 = sum(arr[i][i] for i in range(n))
    d2 = sum(arr[i][n-i-1] for i in range(n))
    return abs(d1 - d2)
```

## [Plus minus - HackerRank solution in Python and c++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Problem Statement : 
        Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.

```cpp
void plusMinus(vector<int> arr) {
    
    float countPositive = 0;
    float countNegative = 0;
    float n = arr.size();

    for(int i;i<n;i++) {
        if (arr[i] > 0)
            countPositive++; 
        else if (arr[i] < 0)
            countNegative++;        
    }
    float countZero = n - countNegative - countPositive;
    cout << setprecision(6) << countPositive/n << endl;
    cout << setprecision(6) << countNegative/n << endl;
    cout << showpoint << setprecision(6) << countZero/n << endl;
}
```

```python
def plusMinus(arr):
    countPositive = 0
    countNegative =0
    for i in range(n):
        if arr[i] > 0:
            countPositive += 1 
        elif arr[i] < 0:
            countNegative += 1
    countZero = n - countPositive-countNegative
    print(countPositive/n)
    print(countNegative/n)
    print(countZero/n)
```

## [Staircase- HackerRank solution in python and c++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Problem Statement: 
Complete the staircase function in the editor below. It should print a staircase as described above.

the staircase has the following parameter(s):

- n: an integer

```cpp
void staircase(int n) {

    for(int i=0;i<n;i++) {
        cout << setfill(' ') << setw(n-(i+1)) << "";
        cout << setfill('#') << setw(i+1) << '#'<< endl;
    }
}
```

```python
# Complete the staircase function below.
def staircase(n):
    for i in range(1, n + 1):
        print(f'{"#"*i:>{n}}')
```

## [Mini-max sum - HackerRank solution in python and C++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

```cpp
void miniMaxSum(vector<int> arr) {

    long long min = LLONG_MAX , max = LLONG_MIN , sum ;
    for(int i = 0 ;i < arr.size() ; ++i)
    {
        sum = 0;
        for(int j = 0; j < arr.size() ; ++j)
        {
            if(i != j)
                sum += arr[j];
        }

        if(sum > max)
            max = sum;

        if (sum < min)
            min = sum;
    }

    cout << min << " " << max << endl;
}
```

```python
def miniMaxSum(arr):
    arr = sorted(arr)
    print(sum(arr[:-1]),sum(arr[1:]))
```

## [Birthday cake Candles- HackerRank Solution in Python and C++](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving)

> You are in charge of the cake for your niece's birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out.

```cpp
int birthdayCakeCandles(vector<int> ar) {

    int max = ar[0];
    int count = 0;
    int n = ar.size();

    for(int i=0;i<n; i++) {
        if(ar[i] > max) {
            max = ar[i];
        }        
    }
    for (int i=0;i<n;i++) {
        if(ar[i]==max) {
            count++;
        }            
    }
    return count;
}
```

```python
def birthdayCakeCandles(ar):
    count = 0 
    maxHeight = max(ar)
    for i in ar:
        if i == maxHeight:
            count += 1
    return count
```

## [Grading Students](https://github.com/codePerfectPlus/competitive-programming-solution/tree/master/HackerRank/Problem%20Solving/11.%20GradingStudents)
> Complete the function grading students in the editor below.
		It should return an integer array consisting of rounded grades

```python
def gradingStudents(grades):
	# Write your code here
	for i in range(len(grades)):
		if grades[i] > 37:
			if(grades[i]%5 >= 3):
				grades[i] = grades[i]+(5-grades[i]%5)
	return grades
```

## Reverse Integer

```python
class Solution:
    def reverse(self, x: int) -> int:
        a = 0
        
        if x >= 0:
            a = int(str(x)[::-1])
        elif x < 0:
            a = -1 * int(str(abs(x))[::-1])
 
        return a
```

Don't Forget to Give A Star. Contributions are welcome.