Skip to content
Programmingoneonone
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Learn everything about programming

HackerRank Running Time of Algorithms problem solution

YASH PAL, 31 July 202430 November 2025

In this HackerRank Running Time of Algorithm problem, Can you modify 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.

HackerRank Running Time of Algorithms problem solution

Problem solution in Python programming.

#!/usr/bin/env python

import sys


def insertion_sort(ar):
    if len(ar) <= 1:
        print(0)
        return(ar)
    else:
        shifts = 0
        
        for j in range(1, len(ar)):
            for i in reversed(range(j)):
                if ar[i + 1] < ar[i]:
                    ar[i], ar[i + 1] = ar[i + 1], ar[i]
                    shifts += 1
                else:
                    break
        
        print(shifts)
        return(ar)
                
if __name__ == '__main__':
    s = int(sys.stdin.readline())
    ar = list(map(int, sys.stdin.readline().split()))
    insertion_sort(ar)

Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in=new Scanner(System.in);
        int N=Integer.parseInt(in.nextLine());
        String[] tokens=in.nextLine().split("[ ]+");
        int[] A=new int[N];
        for(int i=0;i<N;++i)
            A[i]=Integer.parseInt(tokens[i]);
        int ans=0;
        for(int i=1;i<N;++i){
            int val=A[i];
            int j=i-1;
            for(;j>=0 && A[j]>val;--j){
                A[j+1]=A[j];
                ans++;
            }
            A[j+1]=val;
        }
        System.out.println(ans);
    }
}

Problem solution in C++ programming.

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


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int num;
    vector<int> input;
    cin >> num;
    for (int i = 0; i < num; ++i) {
        int tmp;
        cin >> tmp;
        input.push_back(tmp);
    }
    int count = 0;
    for (int i = 1; i < num; ++i) {        
        int val = input[i];
        for (int j = i - 1; j >= 0; --j) {
            if (input[j] > val) {
                input[j + 1] = input[j];
                input[j] = val;
                ++count;
            } else {
                break;
            }
        }
    }
    cout << count << endl;
    
    return 0;
}

Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>

int placeElement(int ar_size, int *  ar) {

    int temp = ar[ar_size-1];
    int shift = 0;
    for(int i=ar_size - 1; i>=0;i--)
    {
        if(ar[i-1] > temp)
        {
            ar[i] = ar[i-1]; 
            shift++;
        } else {
            ar[i]= temp;
            break;
        }
        
    }
   return shift;
    
}


/* Head ends here */
void insertionSort(int ar_size, int *  ar) {

    int shifts=0;
    for(int i = 2; i <= ar_size; i++) {
        shifts += placeElement(i,ar);
        
    }
    printf("%dn", shifts);
}

/* Tail starts here */
int main() {
   
   int _ar_size;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) { 
   scanf("%d", &_ar[_ar_i]); 
}

insertionSort(_ar_size, _ar);
   
   return 0;
}

Problem solution in JavaScript programming.

'use strict';


function binarySearch(arr, n, idx0, idx1) {
    if (n < arr[idx0]) { return idx0; }
    if (arr[idx1] <= n)  { return idx1 + 1; }

    // arr[idx0] <= n < arr[idx1]
    if (idx1 - idx0 <= 1) { return idx0 + 1; }
    var idx = idx0 + Math.floor((idx1 - idx0 + 1) / 2);
    if (n < arr[idx]) { return binarySearch(arr, n, idx0, idx); }
    if (arr[idx] <= n)  { return binarySearch(arr, n, idx, idx1); }

    return idx;
}


function processData(input) {
    var parse_fun = function (s) { return parseInt(s, 10); };
    var lines = input.split('n');
    var N = parse_fun(lines.shift());
    var a = lines.shift().split(' ').splice(0, N).map(parse_fun);

    var res = 0;
    var b = [a[0]];

    for (var i = 1; i < a.length; i++) {
        var idx = binarySearch(b, a[i], 0, b.length - 1);
        res += (i - idx);
        b.splice(idx, 0, a[i]);
    }

    console.log(res);
}


process.stdin.resume();
process.stdin.setEncoding("ascii");
var _input = "";
process.stdin.on("data", function (input) { _input += input; });
process.stdin.on("end", function () { processData(_input); });

Algorithms coding problems solutions AlgorithmsHackerRank

Post navigation

Previous post
Next post

Leave a Reply

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

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes