Algorithms
Problem 01
Solve me First
Complete the function solveMeFirst
to compute the sum of two integers.
def solveMeFirst(a,b):
= int(input())
num1 = int(input())
num2 = solveMeFirst(num1,num2)
res print(res)
Solution
def solveMeFirst(a,b):
return a + b
= int(input())
num1 = int(input())
num2 = solveMeFirst(num1,num2)
res print(res)
Problem 02
Simple Array Sum
Given an array of integers, find the sum of its elements
Solution
def arraySum(arr):
sum = 0
for i in arr:
sum += i
return sum
Problem 03
Compare the Triplets
Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding point on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty.
The rating for Alice’s challenge is the triplet a = (a[0],a[1],a[2]), and the rating for Bob’s challenge is the triplet b = (b[0, b[1], b[2]]).
The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1] and a[2] with b[2].
- if a[i] > b[i], then Alice is awarded 1 point.
- if a[i] < b[i], then Bob is awarded 1 point.
- if a[i] = b[i], then neither person receives a point.
Comparison points is the total points a person earned.
Given a and b, determine their respective comparison points.
def compareTriplets(a, b):
# Write your code here
Solution
def compareTriplets(a,b):
= 0
scoreA = 0
scoreB for aa,bb in zip(a,b):
if aa > bb:
+= 1
scoreA elif aa < bb:
+= 1
scoreB return scoreA, scoreB
Problem 04
A very Big Sum
In this challenge, you are required to calculate and print the sum of the elements in an array, keeping in mind that some of those integers may be quite large.
Complete the aVeryBigSum
function. It must return the sum of all array elements. The function has the following parameters:
- int
ar[n]
: an array of integers. - return
<long>
: the sum of all array elements
def aVeryBigSum(ar):
# Write your code here
Solution
def aVeryBigSum(ar):
= 0
bigNumber for i in ar:
+= i
bigNumber return bigNumber
Problem 05
Diagonal Difference
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix arr
is shown below:
1 2 3
4 5 6 7 8 9
- The left-to-right diagonal = 1 + 5 + 9 = 15.
- The right-to-left diagonal = 3 + 5 + 9 = 17.
- Their absolute difference = |15 - 17| = 2.
def diagonalDifference(arr):
# Write your code here
Solution
def diagonalDifference(arr):
= len(arr)
arr_size = 0
diag1 = 0
diag2 for i in range(arr_size):
+= arr[i][i]
diag1 += arr[i][-(i+1)]
diag2 return abs(diag1-diag2)