Category: permutation

Minimum adjacent swaps required to get Kth smallest number greater than given number

#include using namespace std;  void minSwapsKthLargest(string str, int k){        string res = str;              for (int i = 0; i < k; i++) {        next_permutation(            str.begin(), str.end());    }          int swap_count = 0;              for (int i = 0; i < res.length(); i++) {                  if (res[i] != str[i]) {            int start = i + 1;                          while (res[i] != str[start]) {                                  start++;            }            while (i != start) {                swap(str[start], str[start - 1]);                                                  start--;                swap_count++;            }        }    }          cout

Continue Reading

Find permutation of numbers upto N with a specific sum in a specific range

#include using namespace std;  bool possible(int x, int S, int N){              int minSum = (x * (x + 1)) / 2;              int maxSum = (x * ((2 * N) – x + 1)) / 2;              if (S < minSum || S > maxSum) {        return false;    }    return true;}  void findPermutation(int N, int L,                     int R, int S){              int x = R – L + […]

Continue Reading

Count of distinct permutation of a String obtained by swapping only unequal characters

Given a string find the number of unique permutations that can be obtained by swapping two indices such that the elements at these indices are distinct.NOTE: Swapping is always performed in the original string.Examples:Input: str = “sstt”Output: 5Explaination: Swap str[0] with str[2], string obtained “tsst” which is valid (str[0]!=str[2])Swap str[0] with str[3]. string obtained “tsts”Swap str[1] […]

Continue Reading

Sort a permutation of first N Natural Numbers by swapping pairs satisfying given conditions

def Swap(x, y, p, posOfCurrNum):         posOfCurrNum[p[x]], posOfCurrNum[p[y]] = posOfCurrNum[p[y]], posOfCurrNum[p[x]]    p[x], p[y] = p[y], p[x]    return p, posOfCurrNumdef sortArray(p, n):                 posOfCurrNum = [0] * (n + 1)    for i in range(1, n + 1):        posOfCurrNum[p[i]] = i        ans = []        for i in range(1, n + 1):                                 if (p[i] == i):            continue                        j = posOfCurrNum[i]                        if (abs(i – j) * 2 >= n):            p, posOfCurrNum = Swap(i, j, […]

Continue Reading