HackerRank Absolute Permutation Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Absolute Permutation Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Absolute Permutation Solution
HackerRank Absolute Permutation Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Absolute Permutation


We define P to be a permutation of the first n natural numbers in the range [1, n]. Let  denote the value at position i in permutation P using 1based indexing.

P is considered to be an absolute permutation if [pos[i] – i] = k holds true for every i ∈ [1, n].

Given n and k, print the lexicographically smallest absolute permutation P. If no absolute permutation exists, print -1.


n = 4
k = 2

Create an array of elements from 1 to n, pos = [1. 2, 3, 4]. Using 1 based indexing, create a permutation where every [pos[i] – i] = k. It can be rearranged to [3, 4, 1, 2] so that all of the absolute differences equal k = 2:

pos[i]  i   |pos[i] - i|
  3     1        2
  4     2        2
  1     3        2
  2     4        2

Function Description

Complete the absolutePermutation function in the editor below.

absolutePermutation has the following parameter(s):

  • int n: the upper bound of natural numbers to consider, inclusive
  • int k: the absolute difference between each element’s value and its index


  • int[n]: the lexicographically smallest permutation, or [-1] if there is none

Input Format

The first line contains an integer t, the number of queries.
Each of the next t lines contains 2 spaceseparated integers, n and k.


  • 1 <= t <= 10
  • 1 <= n <= 105
  • 0 <= k < n

Sample Input

STDIN   Function
-----   --------
3       t = 3 (number of queries)
2 1     n = 2, k = 1
3 0     n = 3, k = 0
3 2     n = 3, k = 2

Sample Output

2 1
1 2 3


Test Case 0:

Test Case 1:

Test Case 2:
No absolute permutation exists, so we print -1 on a new line.

HackerRank Absolute Permutation Solution

Absolute Permutation Solution in C

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

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    int i,j,n,t,k;
        scanf("%d %d",&n,&k);
            for(i=0;i<n;i++)printf("%d ",i+1);
            for(j=0;j<k;j++)printf("%d ",((2*k*i)+k+j+1));
            for(j=0;j<k;j++)printf("%d ",((2*k*i)+j+1));
    return 0;

Absolute Permutation Solution in Cpp

#include <bits/stdc++.h>

using namespace std;

int N, K;
int A[100000];

int main()
    int T;
    scanf("%d", &T);
        scanf("%d%d", &N, &K);
        memset(A, -1, sizeof A);
        bool bad=false;
        for(int i=0; i<N; i++)
            if(i-K>=0 && A[i-K]==-1)
            else if(i+K<N && A[i+K]==-1)
            for(int i=0; i<N; i++)
                printf("%d ", A[i]+1);
    return 0;

Absolute Permutation Solution in Java

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int tc = scanner.nextInt();
        for (int t = 0; t < tc; ++t) {
            int n = scanner.nextInt();
            int k = scanner.nextInt();
            print(solve(n, k));

    private static int[] solve(int n, int k) {
        if (k > 0 && n % (2 * k) != 0) {
            return null;
        int[] res = new int[n];
        int shift = k;
        for (int i = 1; i <= n; ++i) {
            res[i - 1] = i + shift;
            if (k > 0 && i % k == 0) {
                shift *= -1;
        return res;

    private static void print(int[] a) {
        if (a == null) {
        for (int i = 0; i < a.length; ++i) {
            if (i > 0) {
                System.out.print(" ");

Absolute Permutation Solution in Python

def solve(N,K):
    if K == 0: return range(1,1+N)
    if N%(2*K): return [-1]
    base = range(K+1,2*K+1) + range(1,1+K)
    ans = []
    Q = N/(2*K)
    for q in xrange( Q ):
        for i in base:
            ans.append( q*2*K + i )
    return ans

rr = raw_input
rrI = lambda: int(rr())
rrM = lambda: map(int,rr().split())
for _ in xrange(rrI()):
    print " ".join(map(str, solve(*rrM())))

Absolute Permutation Solution using JavaScript

function processData(input) {
    var lines = input.split(/\n/);
    var tests = lines.shift();
    for (var line of lines) {
        var info = line.split(/ /).map(Number);
        var n = info.shift();
        var k = info.shift();
        var possibilities = [];
        var bag = {};
        var i = 1;
        var failed = false;
        while (i <= n) {
            var range = [i - k, k + i];
            var found = false;
            loop: for (var j = 0; j < range.length; j++) {
                var choice = range[j];
                if (bag[choice] == undefined && choice > 0 && choice <= n) {
                    bag[choice] = 1;
                    found = true;
                    break loop;
            if (! found) {
                failed = true;

        process.stdout.write((failed ? -1 : possibilities.join(' ')) + "\n")

_input = "";
process.stdin.on("data", function (input) {
    _input += input;

process.stdin.on("end", function () {

Absolute Permutation Solution in Scala

import collection.mutable.LinkedHashSet

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  for (tc <- 0 until lines.next.toInt) {
    val nums = lines.next.split(' ').map(_.toInt)
    val (n, k) = (nums.head, nums.last)
    val used = LinkedHashSet[Int]()
    for (i <- 1 to n) {
      if (ok(i - k)) used += (i - k)
      else if (ok(i + k)) used += (i + k)
      else used.clear()
    println( if (used.size < n) "-1" else used.mkString(" ") )

    def ok(x: Int) = x > 0 && x <= n && !used.contains(x)

Absolute Permutation Solution in Pascal

uses math;
var  n,p,k,i,w,t:longint;

  for w:=1 to t do
     if k=0 then
       for i:=1 to n do
       write(i,' ');
     if n mod (2*k)<>0 then writeln(-1) else

         while(p*k<n) do

         for i:=p*k+k+1 to (p+2)*k do
          write(i,' ');

          for i:=p*k+1 to p*k+k do
          write(i,' ');

Disclaimer: This problem (Absolute Permutation) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment