HackerRank Cards Permutation Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Cards 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.

HackerRank Cards Permutation Solution
HackerRank Cards Permutation Solution

HackerRank Cards Permutation

Task

Alice was given the n integers from 1 to n. She wrote all possible permutations in increasing lexicographical order, and wrote each permutation in a new line. For example, for n = 3, there are 6 possible permutations:

  1. [1, 2, 3]
  2. [1, 3, 2]
  3. [2, 1, 3]
  4. [2, 3, 1]
  5. [3, 1, 2]
  6. [3, 2, 1]

She then chose one permutation among them as her favorite permutation.

After some time, she forgot some elements of her favorite permutation. Nevertheless, she still tried to write down its elements. She wrote a 0 in every position where she forgot the true value.

She wants to know the sum of the line numbers of the permutations which could possibly be her favorite permutation, i.e., permutations which can be obtained by replacing the 0s. Can you help her out?

Since the sum can be large, find it modulo 109 + 7.

Input Format

The first line contains a single integer n.

The next line contains n spaceseparated integers a1a2, . . . , an denoting Alice’s favorite permutation with some positions replaced by 0.

Constraints

  • 1 <= n <= 3 x 105
  • 0 < ai <= n
  • The positive values appearing in [a1, . . . , an] are distinct.

Subtask

For ~33% of the total points, n <= 5000

Output Format

Print a single line containing a single integer denoting the sum of the line numbers of the permutations which could possibly be Alice’s favorite permutation.

Sample Input 0

4
0 2 3 0

Sample Output 0

23

Explanation 0

The possible permutations are [1, 2, 3, 4] and [4, 2, 3, 1]. The permutation [1, 2, 3, 4] occurs on line 1 and the permutation [4, 2, 3, 1] occurs on line 22. Therefore the sum is 1 + 22 = 23.

Sample Input 1

4
4 3 2 1

Sample Output 1

24

Explanation 1

There is no missing number in the permutation. Therefore, the only possible permutation is [4, 3, 2, 1], and it occurs on line 24. Therefore the sum is 24.

HackerRank Cards Permutation Solution

HackerRank Cards Permutation Solution in C

#include<stdio.h>
int n, a[300100], pos[300100], mod = 1e9 + 7, occ[300100], les[300100], grt[300100], st[300100], lst[300100], gst[300100], bitree[300050];
void add(int idx, int val)
{
    while( idx <= n )
    {
        bitree[idx] += val;
        idx += ( idx & -idx );
    }
}
int get(int idx)
{
    int ans = 0;
    while( idx > 0 )
    {
        ans += bitree[idx];
        idx -= ( idx & -idx );
    }
    return ans;
}
long long fact[300100], factsumfr[300100], ans = 0;
long long pwr(long long a, long long b)
{
    if( b == 0 )
    {
        return 1ll;
    }
    long long temp = pwr(a, b/2);
    temp = ( temp * temp ) % mod;
    if( b & 1 )
    {
        temp = ( temp * a ) % mod;
    }
    return temp;
}
long long inv(long long a)
{
    return pwr(a, mod-2);
}
int main()
{
    int i;
    scanf("%d", &n);
    for( i = 1 ; i <= n ; i++ )
    {
        scanf("%d", &a[i]);
        pos[a[i]] = i;
        if(a[i])
        {
            st[a[i]] = 1;
        }
        if(a[i])
        {
            occ[i] = 1;
        }
    }
    fact[0] = 1;
    for( i = 1 ; i <= n ; i++ )
    {
        les[i] = les[i-1] + occ[i], lst[i] = lst[i-1] + st[i], fact[i] = ( fact[i-1] * i ) % mod;
    }
    for( i = n ; i >= 1 ; i-- )
    {
        grt[i] = grt[i+1] + occ[i], gst[i] = gst[i+1] + st[i];
    }
    int k = les[n];
    long long faci = fact[n-k], faci1 = fact[n-k-1], sumfrfr = 0;
    for( i = 1 ; i <= n ; i++ )
    {
        if( a[i] == 0 )
        {
            sumfrfr = ( sumfrfr + ( ( fact[n-i] * ( n - i - grt[i+1] ) ) % mod * inv(n-k-1) ) % mod ) % mod;
            factsumfr[i] = ( factsumfr[i-1] + fact[n-i] ) % mod;    
        }
        else
        {
            factsumfr[i] = factsumfr[i-1];
        }
    }
    for( i = 1 ; i <= n ; i++ )
    {
        long long inc = 0;
        if( st[i] == 0 )
        {
            inc += ( inc + ( ( sumfrfr * ( i - 1 - lst[i] ) ) % mod * fact[n-k-1] ) % mod ) % mod;
        }
        else
        {
            inc = ( inc + ( ( ( n - i + 1 - gst[i] ) * factsumfr[pos[i]] ) % mod * fact[n-k-1] ) % mod ) % mod;
            inc = ( inc + ( ( ( ( ( i - lst[i] ) * fact[n-pos[i]] ) % mod * fact[n-k] ) % mod * ( n - pos[i] + 1 - grt[pos[i]] ) ) % mod * inv(n-k) ) % mod ) % mod;
            add(pos[i], 1);
            int inv1 = get(n) - get(pos[i]);
            inc = ( inc + ( ( fact[n-pos[i]] * fact[n-k] ) % mod * inv1 ) % mod ) % mod;
        }
        ans = ( ans + inc ) % mod;
    }
    ans = ( ans + fact[n-k] ) % mod;
    printf("%lld\n", ans);
    return 0;
}

HackerRank Cards Permutation Solution in Cpp

#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <cstring>
#include <cmath>
#include <memory.h>
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>

using namespace std;

const int nmax = 300 * 1000 + 5;
const int mod = 1000 * 1000 * 1000 + 7;

int n, p[nmax], w[nmax], ff[nmax];
int f[nmax], inv[nmax], rf[nmax];
int fen[nmax];

void upd(int r, int val) {
	for (int i = r; i < nmax; i |= i + 1) {
		fen[i] += val;
		fen[i] %= mod;
	}
}

int get(int r) {
	int ans = 0;
	for (int i = r; i >= 0; i &= i + 1, --i) {
		ans += fen[i];
		ans %= mod;
	}
	return ans;
}

int main() {
//	freopen("input.txt", "r", stdin);
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%d", &p[i]);
	}
	f[0] = rf[0] = inv[1] = 1;
	for (int i = 2; i < nmax; ++i) {
		inv[i] = 1LL * (mod - mod / i) * inv[mod % i] % mod;
	}
	for (int i = 1; i < nmax; ++i) {
		f[i] = 1LL * i * f[i - 1] % mod;
		rf[i] = 1LL * inv[i] * rf[i - 1] % mod;
	}
	int ans = 0, tot = 0;
	for (int i = 1; i <= n; ++i) {
		w[p[i]] = 1;
		ff[p[i]] = 1;
		tot += p[i] == 0;
	}
	w[0] = 0;
	for (int i = 1; i <= n; ++i) {
		w[i] = 1 - w[i];
		w[i] += w[i - 1];
	}
/*	int ord[11] = {};
	for (int j = 1; j <= n; ++j) {
		ord[j] = j;
	}
	long long c = 0, d = 0;
	do {
		bool ok = true;
		for (int i = 1; i <= n; ++i) {
			ok &= p[i] == 0 || ord[i] == p[i];
		}
		d += 1;
		if (ok) {
			c += d;
		}
	} while (next_permutation(ord + 1, ord + n + 1));
	cout << c % mod << endl;*/
	int ANS = 0;
	for (int i = n, c = 0, d = 0; i >= 1; --i) {
		if (p[i] > 0) {
			d = (d + w[n] - w[p[i]]) % mod;
			ANS = (ANS + 1LL * f[n - i] * f[tot] % mod * get(p[i])) % mod;
			if (c > 0) {
				ANS = (ANS + 1LL * f[n - i] * f[tot - 1] % mod * w[p[i]] % mod * c) % mod;
			}
			upd(p[i], +1);
		} else {
			ANS = (ANS + 1LL * f[n - i] * f[tot] % mod * inv[2] % mod * c) % mod;
			ANS = (ANS + 1LL * f[n - i] * d % mod * f[tot - 1]) % mod;
			c += 1;
		}
	}
/*	for (int i = 1; i <= n; ++i) {
		if (p[i] > 0) {
			int x = p[i];
			for (int j = i + 1; j <= n; ++j) {
				if (p[j] < x && p[j] != 0) {
					ans = (ans + 1LL * f[n - i] % mod * f[tot]) % mod;
				} else if (p[j] == 0) {
					ans = (ans + 1LL * f[n - i] * w[x] % mod * f[tot - 1]) % mod;
				}
			}
			for (int j = i - 1; j > 0; --j) {
				if (p[j] == 0) {
					ans = (ans + 1LL * f[n - j] * (w[n] - w[x]) % mod * f[tot - 1]) % mod;
				}
			}
		} else {
			for (int j = i + 1; j <= n; ++j) {
				if (p[j] == 0) {
					ans = (ans + 1LL * f[n - i] * f[tot] % mod * inv[2]) % mod;
				}
			}
		}
	}*/
	cout << (ANS + f[tot]) % mod << endl;
//	cout << (ans + f[tot]) % mod << endl;// + f[tot] << endl;
	return 0;
}

HackerRank Cards Permutation Solution in Java

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    private static final int modulus = 1000000007;
    private static int[] knowns;              // known numbers, (input order)
    private static int[] gkArr;               // gkArr[k] number of knowns after k in x s.t k>i_i
    private static int[] guArr;               // guArr[k] number of unknowns s.t. k>u
    private static int[] remainingUnknownsArr;// number of unknowns in x[n-1-i:x.length]
    private static long[] factorials;         // factorials[i] = i! % modulus
    private static long[] runningDiffs;        // sum over remaining k of (U.len-guArr)
    private static long[] EO;                 // Expected ordinals
    //O(n+klgk) sum = |U|!(1+sum over n of n!*EO_n) % modulus
    static long solve(int[] x) { //O(n + klgk)
        int n = x.length;
        long sum = 1L;
        factorialsInit(n); //O(n)
        int[] U = getUnknownInts(n, x); //O(n) - relies on x
        knownsInit(x); //O(n) - relies on x
        gkInit(n); //O(klgk) - relies on knowns, x
        guInit(n, U); //O(n) - relies on unknowns, x
        unknownsRemainingInit(x); //O(n) -relies on x
        runningDiffsInit(x, U); //O(n) -relies on gu, x
        EOInit(x, n, U); //O(n) - relies on knowns, unknowns, gk, gu, running sums, x
        for(int i = 1; i < n; i++) //O(n)                   
            sum = addMod(sum, mulMod(EO[i], factorials[i]));
        sum = mulMod(sum, factorials[U.length]);
        return sum;
    }
    //O(klgk) setup GOOD
    private static void gkInit(int n) {
        gkArr = new int[n+1];
        int[][] arrs = new int[2][knowns.length];
        arrs[0] = Arrays.copyOfRange(knowns, 0, knowns.length); 
        int subLen = 1;
        int b = 0;
        do {
            int i = 0;
            subLen *= 2;
            int j = (subLen >>> 1);
            int endSub = subLen;
            int counter = 0;
            int imin = Math.min(knowns.length, endSub - (subLen>>>1));
            int jmin = Math.min(knowns.length, endSub);
            while(counter < knowns.length) {
                if(j < jmin && i < imin && arrs[b][i] < arrs[b][j]) {
                    arrs[(b+1)%2][counter] = arrs[b][i];
                    gkArr[arrs[b][i]] += Math.max(0, (counter++)-i++);
                } else if(j < jmin) {
                    arrs[(b+1)%2][counter] = arrs[b][j];
                    gkArr[arrs[b][j]] += Math.max(0, (counter++)-j++);
                } else if(i < imin) {
                    arrs[(b+1)%2][counter] = arrs[b][i];
                    gkArr[arrs[b][i]] += Math.max(0, (counter++)-i++);
                } else {
                    endSub += subLen;
                    i = j;
                    j += (subLen>>>1);
                    imin = Math.min(knowns.length, endSub - (subLen>>>1));
                    jmin = Math.min(knowns.length, endSub);
                }
            }
            b = (b+1)%2;
        } while (subLen < knowns.length);
    }
    //O(n) setup
    private static void runningDiffsInit(int[] x, int[] U) { //Sum over k of U_g
        runningDiffs = new long[x.length];
        runningDiffs[0] = (x[x.length-1] == 0) ? 0 : U.length - guArr[x[x.length-1]]; 
        for(int i = 1; i < x.length; i++) {
            if(x[x.length-1-i] != 0)
                runningDiffs[i] = U.length - guArr[x[x.length-1-i]];
            runningDiffs[i] = addMod(runningDiffs[i], runningDiffs[i-1]);
        }
    }
    //O(n) setup GOOD
    private static void unknownsRemainingInit(int[] x) {
        remainingUnknownsArr = new int[x.length];
        int u = 0;
        for(int i = x.length-1; i >= 0; i--)
            remainingUnknownsArr[i] = (x[i] == 0) ? u++ : u; //INCLUSIVE
    }
    //O(n) setup GOOD
    private static void guInit(int n, int[] U) {
        guArr = new int[n+1];
        int k = 0;
        int u = 0;
        for(int i = 0; i < U.length; i++) {
            while( k <= U[i])
                guArr[k++] = u;
            u++;
        }
         while( k < guArr.length)
                guArr[k++] = u;
    }
    //O(n) setup
    private static void EOInit(int[] x, int n , int[] U) {
        EO = new long[x.length];
        long d = 0L;
        long invertedUlen = binaryExpMod(U.length, Solution.modulus-2L);
        for(int i = 1; i < n; i++) {
            if(x[n-1-i] == 0) {
                //from unknown perms 
                EO[i] = mulMod(remainingUnknownsArr[n-1-i], 500000004L); // div by 2
                //from knowns DP 
                d = mulMod(runningDiffs[i], invertedUlen);
                EO[i] = addMod(EO[i], d);
            } else {
                //fraction of unknowns larger
                d = mulMod(guArr[x[n-1-i]], invertedUlen);
                EO[i] = addMod(EO[i], mulMod(remainingUnknownsArr[n-1-i], d));
                //number of knowns larger
                EO[i] = addMod(EO[i], gkArr[x[n-1-i]]);
            }
        }
    }
    //O(lgn) GOOD
    private static long binaryExpMod(long l, long pow) { //l^(modulus-2) mod modulus
        if (l == 0L && pow != 0L)
            return 0L;
        long[] squares = new long[30];         //30 = ciel(lg(modulus-2)) > ciel(lg(n))
        squares[0] = l % Solution.modulus;
        for(int i = 1; i < 30; i++) 
            squares[i] = mulMod(squares[i-1], squares[i-1]);
        long result = 1L;
        int i = 0;
        while(pow != 0L) {
            if((pow & 1L) == 1L)
                result = mulMod(result, squares[i]);
            i++;
            pow >>>= 1;
        }
        return result;
    }
    //O(n) setup 
    private static void factorialsInit(int n) {
        factorials = new long[n+1];
        factorials[0] = 1L;
        factorials[1] = 1L;
        for(int i = 2; i <= n; i++)
            factorials[i] = Solution.mulMod(factorials[i-1], i);
    }
    //O(1) GOOD
    private static long mulMod(long result, long l) {
        return ( (result%Solution.modulus) * (l%Solution.modulus) )%Solution.modulus;
    }
    //O(1) GOOD
    private static long addMod(long result, long l) {
        return ( (result%Solution.modulus) + (l%Solution.modulus) )%Solution.modulus;
    }
    //O(n) setup GOOD
    private static int[] getUnknownInts(int n, int[] x) { //O(n) but setup so insignif
        int[] ints = new int[n];    
        for(int i = 1; i <= n; i++)
            ints[i-1] = i;
        for(int i: x)
            if(i != 0) {
                ints[i-1] = 0;
                n--;
            }
        int[] intsOut = new int[n];
        n = 0; //becomes index
        for(int i: ints) 
            if(i != 0)
                intsOut[n++] = i;
        return intsOut;
    }
    //O(n) setup GOOD
    private static void knownsInit(int[] x) {
        int counter = 0;
        for(int a: x) 
            if(a > 0)
                counter++;
        knowns = new int[counter];
        counter = 0;
        for(int a: x)
            if(a > 0)
                knowns[counter++] = a;
    } 
    
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] a = new int[n];

        String[] aItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int aItem = Integer.parseInt(aItems[i]);
            a[i] = aItem;
        }

        long result = solve(a);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}

HackerRank Cards Permutation Solution in Python

#!/bin/python

import math
import os
import random
import re
import sys

# Complete the solve function below.
MAXN = 3e5 + 5
mod = int(1e9 + 7)
inv2 = (mod + 1) >> 1


c = []
pre = []
fac = []
N = 0
count = 0
lex = 0


def add(a, b):
    a += b
    return a - mod if a >= mod else a


def pop(a, b):
    a -= b
    return a + mod if a < 0 else a


def mul(a, b):
    return (a * b) % mod


def lowbit(i):
    return i & (-i)


def update(o, v):
    i = o + 1
    while i <= N:
        c[i] += v
        i += lowbit(i)


def calc(o):
    sum = 0
    i = o + 1
    while i >= 1:
        sum += c[i]
        i -= lowbit(i)
    return sum


def prepare():
    global count, lex

    for i in range(1, N + 1):
        a[i] -= 1
        count += 1 if (a[i] == -1) else 0
        if a[i] >= 0:
            pre[a[i]] = 1

    fac[0] = 1
    for i in range(1, N + 1):
        fac[i] = mul(i, fac[i - 1])
    for i in range(1, N):
        pre[i] += pre[i - 1]

    lex = mul(mul(N, pop(N, 1)), inv2)
    for i in range(1, N + 1):
        if a[i] != -1:
            lex = pop(lex, a[i])
    # print('prep done:')
    # print('a: {}'.format(a))
    # print('pre: {}'.format(pre))
    # print('fac: {}'.format(fac))
    # print('lex: {}'.format(lex))
    # print('count: {}'.format(count))


def cal2(n):
    return mul(mul(n, pop(n, 1)), inv2)


def solve(x):
    global count, lex

    prepare()

    cur = 0
    ans = 0
    for i in range(1, N + 1):
        if a[i] != -1:
            sum = mul(fac[count], a[i] - calc(a[i]))
            if count >= 1:
                sum = pop(sum, mul(fac[count - 1],
                                   mul(cur, a[i] + 1 - pre[a[i]])))
            sum = mul(sum, fac[N - i])
            ans = add(ans, sum)
            update(a[i], 1)
            lex = pop(lex, pop(N - 1 - a[i], pop(pre[N-1], pre[a[i]])))
        else:
            sum = mul(lex, fac[count - 1])
            if count >= 2:
                sum = pop(sum, mul(fac[count - 2], mul(cur, cal2(count))))
            sum = mul(sum, fac[N - i])
            ans = add(ans, sum)
            cur += 1
    return add(ans, fac[count])


if __name__ == '__main__':
    N = int(raw_input())

    a = map(int, raw_input().rstrip().split())
    a.insert(0, 0)

    for i in range(len(a)):
        pre.append(0)
        fac.append(0)
        c.append(0)

    result = solve(a)

    print(result)

HackerRank Cards Permutation Solution using JavaScript

'use strict';

const fs = require('fs');
const _ = require('underscore');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

const MAXN = BigInt(3e5 + 5),
      mod = BigInt(1e9 + 7),
      inv2 = (mod + 1n) >> 1n;

  let c = [],
      pre = [],
      fac = [],
      N = 0n,
      count = 0n,
      lex = 0n,
      a, cur, ans, sum;

function readLine() {
    return inputString[currentLine++];
}


function add(a, b) {
  a += b;
  return a >= mod ? a - mod : a;
}

function pop(a, b) {
  a -= b;
  return a < 0n ? a + mod : a;
}

function mul(a, b) {
  return (a * b) % mod;
}

function lowbit(i) {
  return i & (-i)
}

function update (o, v) {
  let i = o + 1n;
  while (i <= N) {
    c[i] += v;
    i += lowbit(i)
  }
}

function calc(o) {
  let s = 0n, i = o + 1n;
  while (i >= 1n) {
    s += c[i]
    i -= lowbit(i);
  } 
  return s
}

function* range(start, end) {
    for (let i = start; i < end; i++) {
        yield i;
    };
};

function cal2(n) {
  return mul(mul(n, pop(n, 1n)), inv2)
}

function prepare() {
  for (let i of range(1n, N + 1n)) {
    a[i] -= 1n;
    if (a[i] == -1n) count += 1n;
    if (a[i] >= 0n) pre[a[i]] = 1n;
  }
  fac[0] = 1n;
  for (let i of range(1n, N + 1n)) {
    fac[i] = mul(i, fac[i - 1n])
  }
  for (let i of range(1n, N)) {
    pre[i] += pre[i - 1n];
  }
  lex = mul(mul(N, pop(N, 1n)), inv2);
  for (let i of range(1n, N + 1n)) {
    if (a[i] != -1n) lex = pop(lex, a[i])
  }
}

function solve(x) {
  prepare()
  cur = 0n
  ans = 0n
  for (let i of range(1n, N + 1n)) {
    if (a[i] != -1n) {
      sum = mul(fac[count], a[i] - calc(a[i]))
      if (count >= 1n) {
        sum = pop(sum, mul(fac[count - 1n], mul(cur, a[i] + 1n - pre[a[i]])))
      }
      sum = mul(sum, fac[N - i])
      ans = add(ans, sum)
      update(a[i], 1n)
      lex = pop(lex, pop(N - 1n - a[i], pop(pre[N - 1n], pre[a[i]])))
    } else {
      sum = mul(lex, fac[count - 1n])
      if (count >= 2n) {
        sum = pop(sum, mul(fac[count - 2n], mul(cur, cal2(count))))
      }
      sum = mul(sum, fac[N - i])
      ans = add(ans, sum)
      cur += 1n
    }
  }
  return add(ans, fac[count])
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
    N = BigInt(parseInt(readLine(), 10));
    a = readLine().split(' ').map(aTemp => BigInt(parseInt(aTemp, 10, 64)));
        let result;

        a.unshift(0n)
        for (let i in _.range(a.length)) {
          pre.push(0n);
          fac.push(0n);
          c.push(0n);
        };

        result = solve(a);

    ws.write(result + "\n");

    ws.end();
}

HackerRank Cards Permutation Solution in Scala

HackerRank Cards Permutation Solution in Pascal

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

Sharing Is Caring