Running Time of Algorithms – HackerRank Solution

In this post, we will solve Running Time of Algorithms HackerRank Solution. This problem (Running Time of Algorithms) is a part of HackerRank Problem Solving series.


In a previous challenge you implemented the Insertion Sort algorithm. It is a simple sorting algorithm that works well with small or mostly sorted data. However, it takes a long time to sort large unsorted data. To see why, we will analyze its running time.

Running Time of Algorithms
The running time of an algorithm for a specific input depends on the number of operations executed. The greater the number of operations, the longer the running time of an algorithm. We usually want to know how many operations an algorithm will execute in proportion to the size of its input, which we will call N.

What is the ratio of the running time of Insertion Sort to the size of the input? To answer this question, we need to examine the algorithm.

Analysis of Insertion Sort
For each element V in an array of N numbers, Insertion Sort compares the number to those to its left until it reaches a lower value element or the start. At that point it shifts everything to the right up one and inserts V into the array.

How long does all that shifting take?

In the best case, where the array was already sorted, no element will need to be moved, so the algorithm will just run through the array once and return the sorted array. The running time would be directly proportional to the size of the input, so we can say it will take N time.

However, we usually focus on the worst-case running time (computer scientists are pretty pessimistic). The worst case for Insertion Sort occurs when the array is in reverse order. To insert each number, the algorithm will have to shift over that number to the beginning of the array. Sorting the entire array of N numbers will therefore take 1 + 2 + . . . + (N – 1) operations, which is N(N – 1)/2 (almost N2/2). Computer scientists just round that up (pick the dominant term) to N2 and say that Insertion Sort is an “N2 time” algorithm.

What this means
The running time of the algorithm against an array of N elements is N2. For 2N elements, it will be 4N2. Insertion Sort can work well for small inputs or if you know the data is likely to be nearly sorted, like check numbers as they are received by a bank. The running time becomes unreasonable for larger inputs.

Can you modify your previous Insertion Sort implementation to keep track of the number of shifts it makes while sorting? The only thing you should print is the number of shifts made by the algorithm to completely sort the array. A shift occurs when an element’s position changes in the array. Do not shift an element if it is not necessary.

Function Description

Complete the runningTime function in the editor below.

runningTime has the following parameter(s):

  • int arr[n]: an array of integers


  • int: the number of shifts it will take to sort the array

Input Format

The first line contains the integer n, the number of elements to be sorted.
The next line contains n integers of arr[arr[0] . . . arr[n – 1]].


  • 1 <= n <= 1001
  • -10000 <= a[i] <= 10000, where i ∈ {0 . . (n – 1)}

Sample Input

STDIN       Function
-----       --------
5           arr[] size n =5
2 1 3 1 2   arr = [2, 1, 3, 1, 2]

Sample Output



Iteration   Array      Shifts
0           2 1 3 1 2
1           1 2 3 1 2     1
2           1 2 3 1 2     0
3           1 1 2 3 2     2
4           1 1 2 2 3     1

Total                     4

Solution – Running Time of Algorithms – HackerRank Solution


#include <iostream>
#include <stdlib.h>

using namespace std;
void insertionSort(int N, int arr[]) {
    int i,j,value;
    int shifted = 0;
    for(i=1;i<N;i++) // first value @ i = 0 is always technically sorted
        while(j>=0 && value<arr[j])
        // it's j+1 because j is decremented on last run of while loop
    cout << shifted << endl;
int main(void) {

    int N;
    cin >> N;
    int arr[N], i;
    for(i = 0; i < N; i++) {
        cin >> arr[i];

    insertionSort(N, arr);

    return 0;


import sys

def insertionSort1(start, arr):
    probe = arr[start]
    changed = 0
    for ind in range(start-1, -1, -1):
        if arr[ind] > probe:
            changed += 1
            arr[ind+1] = arr[ind]
            arr[ind+1] = probe
    if arr[0] > probe:
        arr[0] = probe
    return changed

def insertionSort2(n, arr):
    res = 0
    for ind in range(1, len(arr)):
        res += insertionSort1(ind, arr)
        #print(" ".join(map(str, arr)))
    return res

def runningTime(arr):
    return insertionSort2(len(arr), arr)
if __name__ == "__main__":
    n = int(input().strip())
    arr = list(map(int, input().strip().split(' ')))
    result = runningTime(arr)


import java.util.*;

public class Solution {

    public static void insertionSort(int[] A){
        int shifts = 0;
        for(int i = 1; i < A.length; i++){
            int value = A[i];
            int j = i - 1;
            while(j >= 0 && A[j] > value){
                A[j + 1] = A[j];
                j = j - 1;
            A[j + 1] = value;
            shifts += i - (j+1);


    static void printArray(int[] ar) {
        for(int n: ar){
            System.out.print(n+" ");
    public static void main(String[] args) {
        Scanner in = new Scanner(;
        int n = in.nextInt();
        int[] ar = new int[n];
        for(int i=0;i<n;i++){

Note: This problem (Running Time of Algorithms) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *