DEV Community

Cover image for HackerRank Algorithms Solutions using Python and C++(CPP)
Deepak Raj
Deepak Raj

Posted on • Edited on • Originally published at codeperfectplus.com

HackerRank Algorithms Solutions using Python and C++(CPP)

This page is moved to codeperfectplus. Please checkout for latest code.
Check out the link here

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++)

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 logo codeperfectplus / competitive-programming-solution

Competitive Programming solution in Python/JavaScript/C++ 🚀

Problems

Solve Me First - HackerRank solution in Python and C++

Problem Statement: the sum of the above two integers

int solveMeFirst(int a, int b) {
 // Hint: Type return a+b; below:
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode
def solveMeFirst(a:int,b:int):
    # Hint: Type return a+b below
    return a + b
Enter fullscreen mode Exit fullscreen mode

Simple Array Sum - HackerRank solution in Python and c++

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

int simpleArraySum(vector<int> ar) {
    /*
     * Write your code here.
     */
    return accumulate(ar.begin(), ar.end(), 0);
}
Enter fullscreen mode Exit fullscreen mode
def simpleArraySum(ar:list):
    return(sum(ar))
Enter fullscreen mode Exit fullscreen mode

Compare the Triplets - HackerRank solution in Python and c++

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
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;
}
Enter fullscreen mode Exit fullscreen mode
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]
Enter fullscreen mode Exit fullscreen mode

A very big sum - HackerRank solution in Python and c++

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.
long aVeryBigSum(vector<long> ar) {

    long long int total =  accumulate(ar.begin(), ar.end(), 0ll);
    return total;
}
Enter fullscreen mode Exit fullscreen mode
def aVeryBigSum(ar):
    return sum(ar)
Enter fullscreen mode Exit fullscreen mode

Diagonal difference - HackerRank solution in Python and c++

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

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); 
}
Enter fullscreen mode Exit fullscreen mode
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)
Enter fullscreen mode Exit fullscreen mode

Plus minus - HackerRank solution in Python and c++

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.

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;
}
Enter fullscreen mode Exit fullscreen mode
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)
Enter fullscreen mode Exit fullscreen mode

Staircase- HackerRank solution in python and c++

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
void staircase(int n) {

    for(int i=0;i<n;i++) {
        cout << setfill(' ') << setw(n-(i+1)) << "";
        cout << setfill('#') << setw(i+1) << '#'<< endl;
    }
}
Enter fullscreen mode Exit fullscreen mode
# Complete the staircase function below.
def staircase(n):
    for i in range(1, n + 1):
        print(f'{"#"*i:>{n}}')
Enter fullscreen mode Exit fullscreen mode

Mini-max sum - HackerRank solution in python and C++

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.

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;
}
Enter fullscreen mode Exit fullscreen mode
def miniMaxSum(arr):
    arr = sorted(arr)
    print(sum(arr[:-1]),sum(arr[1:]))
Enter fullscreen mode Exit fullscreen mode

Birthday cake Candles- HackerRank Solution in Python and C++

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.

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;
}
Enter fullscreen mode Exit fullscreen mode
def birthdayCakeCandles(ar):
    count = 0 
    maxHeight = max(ar)
    for i in ar:
        if i == maxHeight:
            count += 1
    return count
Enter fullscreen mode Exit fullscreen mode

Grading Students

Complete the function grading students in the editor below.
It should return an integer array consisting of rounded grades

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
Enter fullscreen mode Exit fullscreen mode

Reverse Integer

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)