Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Smallest number by rearranging digits of a given number
Next article icon

Rearrange digits of a number to remove any subsequence of another given number

Last Updated : 10 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two numeric strings N and K (K ? N), where digits of K are in non-decreasing order, the task is to rearrange digits of N such that K does not appear as a subsequence in N. If it is not possible to obtain such a permutation, print “-1”. Otherwise print any such valid permutation of N.

Examples:

Input: N = 93039373637, K = 339
Output: 97093736333

Input: N=965, K=55
Output: 965

Naive Approach: The simplest approach is to generate every permutation of N and check for each permutation, if K appears as a subsequence in it or not. If found to be false for any permutation, print that permutation. 
Time Complexity: O(N*N!)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized based on the observation that the digits of K are in non-decreasing order. Therefore, rearrange the digits of N in decreasing order by sorting. Follow the steps below to solve the problem:

  • Store the frequency of digits of N and K in HashMaps M1 and M2, respectively.
  • Iterate over the range [0, 9] using a variable, say i, to check if K has any digit with more occurrences than in N. If M2[i] > M1[i], then print N and return.
  • Again, iterate over the range [0, 9] using a variable i to check if K contains only 1 distinct digit. If M2[i] is the same as length(K), then print “-1” and return. 
  • For all other cases, sort N in decreasing order and then print N.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find a permutation of
// number N such that the number K does
// not appear as a subsequence in N
void findArrangement(string n, string k)
{
 
    // Stores frequency of digits of N
    unordered_map<char, int> um1;
    for (int i = 0; i < n.size(); i++) {
        um1[n[i]]++;
    }
 
    // Stores frequency of digits of K
    unordered_map<char, int> um2;
    for (int i = 0; i < k.size(); i++) {
        um2[k[i]]++;
    }
 
    // Check if any digit in K has
    // more occurrences than in N
    for (int i = 0; i <= 9; i++) {
        char ch = '0' + i;
 
        // If true, print N and return
        if (um2[ch] > um1[ch]) {
            cout << n;
            return;
        }
    }
 
    // Check if K contains only a
    // single distinct digit
    for (int i = 0; i <= 9; i++) {
        char ch = '0' + i;
 
        // If true, print -1 and return
        if (um2[ch] == k.size()) {
            cout << -1;
            return;
        }
    }
 
    // For all other cases, sort N
    // in decreasing order
    sort(n.begin(), n.end(),
         greater<char>());
 
    // Print the value of N
    cout << n;
}
 
// Driver Code
int main()
{
    string N = "93039373637", K = "339";
 
    // Function Call
    findArrangement(N, K);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find a permutation of
// number N such that the number K does
// not appear as a subsequence in N
static void findArrangement(String n, String k)
{
 
    // Stores frequency of digits of N
    HashMap<Character,Integer> um1 = new HashMap<Character,Integer>();
    for (int i = 0; i < n.length(); i++)
    {
         if(um1.containsKey(n.charAt(i)))
         {
                um1.put(n.charAt(i), um1.get(n.charAt(i))+1);
            }
            else
            {
                um1.put(n.charAt(i), 1);
            }
    }
 
    // Stores frequency of digits of K
    HashMap<Character,Integer> um2 = new HashMap<Character,Integer>();
    for (int i = 0; i < k.length(); i++) {
         if(um2.containsKey(k.charAt(i))){
                um2.put(k.charAt(i), um2.get(k.charAt(i))+1);
            }
            else{
                um2.put(k.charAt(i), 1);
            }
    }
 
    // Check if any digit in K has
    // more occurrences than in N
    for (int i = 0; i <= 9; i++)
    {
        char ch = (char) ('0' + i);
 
        // If true, print N and return
        if (um2.containsKey(ch) && um1.containsKey(ch)
                && um2.get(ch) > um1.get(ch))
        {
            System.out.print(n);
            return;
        }
    }
 
    // Check if K contains only a
    // single distinct digit
    for (int i = 0; i <= 9; i++)
    {
        char ch = (char) ('0' + i);
 
        // If true, print -1 and return
        if (um2.containsKey(ch) && um2.get(ch) == k.length())
        {
            System.out.print(-1);
            return;
        }
    }
 
    // For all other cases, sort N
    // in decreasing order
    n = sortString(n);
 
    // Print the value of N
    System.out.print(n);
}
static String sortString(String inputString)
{
   
    // convert input string to char array
    char tempArray[] = inputString.toCharArray();
 
    // sort tempArray
    Arrays.sort(tempArray);
   
    // return new sorted string
    return new String(new StringBuffer(new String(tempArray)).reverse());
}
   
// Driver Code
public static void main(String[] args)
{
    String N = "93039373637", K = "339";
 
    // Function Call
    findArrangement(N, K);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program for the above approach
 
# Function to find a permutation of
# number N such that the number K does
# not appear as a subsequence in N
def findArrangement(n, k) :
 
    # Stores frequency of digits of N
    um1 = dict.fromkeys(n, 0);
     
    for i in range(len(n)):
        um1[n[i]] += 1;
 
    # Stores frequency of digits of K
    um2 = dict.fromkeys(k, 0);
     
    for i in range(len(k)) :
        um2[k[i]] += 1;
 
    # Check if any digit in K has
    # more occurrences than in N
    for i in range(10) :
        ch = chr(ord('0') + i);
 
        if ch in um2 :
           
            # If true, print N and return
            if (um2[ch] > um1[ch]) :
                print(n, end = "");
                return;
 
    # Check if K contains only a
    # single distinct digit
    for i in range(10) :
        ch = chr(ord('0') + i);
     
        if ch in um2 :
         
            # If true, print -1 and return
            if (um2[ch] == len(k)) :
                print(-1, end = "");
                return;
 
    # For all other cases, sort N
    # in decreasing order
    n = list(n)
    n.sort(reverse = True)
     
    # Print the value of N
    print("".join(n));
 
# Driver Code
if __name__ == "__main__" :
 
    N = "93039373637"; K = "339";
 
    # Function Call
    findArrangement(N, K);
 
    # This code is contributed by AnkThon
 
 

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find a permutation of
  // number N such that the number K does
  // not appear as a subsequence in N
  static void findArrangement(string n, string k)
  {
 
    // Stores frequency of digits of N
    Dictionary<char, int> um1 = new Dictionary<char, int>();
    for (int i = 0; i < n.Length; i++)
    {
      if(um1.ContainsKey(n[i]))
      {
        um1[n[i]]++;
      }
      else
      {
        um1[n[i]] = 1;
      }
    }
 
    // Stores frequency of digits of K
    Dictionary<char, int> um2 = new Dictionary<char, int>();
    for (int i = 0; i < k.Length; i++)
    {
      if(um2.ContainsKey(k[i]))
      {
        um2[k[i]]++;
      }
      else
      {
        um2[k[i]] = 1;
      }
    }
 
    // Check if any digit in K has
    // more occurrences than in N
    for (int i = 0; i <= 9; i++)
    {
      char ch = (char) ('0' + i);
 
      // If true, print N and return
      if (um2.ContainsKey(ch) && um1.ContainsKey(ch)
          && um2[ch] > um1[ch])
      {
        Console.Write(n);
        return;
      }
    }
 
    // Check if K contains only a
    // single distinct digit
    for (int i = 0; i <= 9; i++)
    {
      char ch = (char) ('0' + i);
 
      // If true, print -1 and return
      if (um2.ContainsKey(ch) && um2[ch] == k.Length)
      {
        Console.Write(-1);
        return;
      }
    }
 
    // For all other cases, sort N
    // in decreasing order
    n = sortString(n);
 
    // Print the value of N
    Console.Write(n);
  }
 
  static string sortString(string inputString)
  {
 
    // convert input string to char array
    char[] tempArray = inputString.ToCharArray();
 
    // sort tempArray
    Array.Sort(tempArray);
    Array.Reverse(tempArray);
 
    // return new sorted string
    return new string(tempArray);
  }
 
  // Driver codew
  static void Main()
  {
    string N = "93039373637", K = "339";
 
    // Function Call
    findArrangement(N, K);
  }
}
 
// This code is contributed by divyeshrabadiya07
 
 

Javascript




<script>
 
// Javascript program for the above approach
// Function to find a permutation of
// number N such that the number K does
// not appear as a subsequence in N
function findArrangement(n, k)
{
 
  // Stores frequency of digits of N
  var um1 = new Map();
  for (var i = 0; i < n.length; i++)
  {
    if(um1.has(n[i]))
    {
      um1.set(n[i], um1.get(n[i])+1);
    }
    else
    {
        um1.set(n[i], 1);
    }
  }
   
  // Stores frequency of digits of K
  var um2 = new Map();
  for (var i = 0; i < k.length; i++)
  {
    if(um2.has(k[i]))
    {
        um2.set(k[i], um2.get(k[i])+1);
    }
    else
    {
        um2.set(k[i], 1);
    }
  }
   
  // Check if any digit in K has
  // more occurrences than in N
  for (var i = 0; i <= 9; i++)
  {
    var ch = String.fromCharCode('0'.charCodeAt(0) + i);
     
    // If true, print N and return
    if (um2.has(ch) && um1.has(ch)
        && um2.get(ch) > um1.get(ch))
    {
      Console.Write(n);
      return;
    }
  }
   
  // Check if K contains only a
  // single distinct digit
  for (var i = 0; i <= 9; i++)
  {
    var ch =  String.fromCharCode('0'.charCodeAt(0) + i);
     
    // If true, print -1 and return
    if (um2.has(ch) && um2.get(ch) == k.length)
    {
      document.write(-1);
      return;
    }
  }
   
  // For all other cases, sort N
  // in decreasing order
  n = sortString(n);
   
  // Print the value of N
  document.write(n);
}
function sortString(inputString)
{
  // convert input string to char array
  var tempArray = inputString.split('');
   
  // sort tempArray
  tempArray.sort();
  tempArray.reverse();
   
  // return new sorted string
  return tempArray.join('');
}
 
// Driver codew
var N = "93039373637", K = "339";
 
// Function Call
findArrangement(N, K);
 
// This code is contributed by itsok.
 
</script>
 
 
Output: 
99776333330

 

Time Complexity: O(L*log (L)), where L is the size of the string N
Auxiliary Space: O(L)



Next Article
Smallest number by rearranging digits of a given number

A

aditya7409
Improve
Article Tags :
  • DSA
  • Greedy
  • Mathematical
  • Sorting
  • Strings
  • cpp-unordered_map
  • frequency-counting
Practice Tags :
  • Greedy
  • Mathematical
  • Sorting
  • Strings

Similar Reads

  • Smallest number by rearranging digits of a given number
    Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of a given number. Examples: Input: n = 846903Output: 304689Input: n = 55010Output: 10055Input: n = -40505Output: -55400Steps to find the smallest number. Count the frequency of each digit in the number.If i
    7 min read
  • Minimize removals to remove another string as a subsequence of a given string
    Given two strings str and X of length N and M respectively, the task is to find the minimum characters required to be removed from the string str such that string str doesn't contain the string X as a subsequence. Examples: Input: str = "btagd", X = "bad"Output: 1Explanation:String "btag" has does n
    14 min read
  • Maximum K-digit number possible from subsequences of two given arrays
    Given two arrays arr1[] and arr2[] of length M and N consisting of digits [0, 9] representing two numbers and an integer K(K ? M + N), the task is to find the maximum K-digit number possible by selecting subsequences from the given arrays such that the relative order of the digits is the same as in
    12 min read
  • Number of digits to be removed to make a number divisible by 3
    Given a very large number num (1 <= num <= 10^1000), print the number of digits that needs to be removed to make the number exactly divisible by 3. If it is not possible then print -1. Examples : Input: num = "1234"Output: 1Explanation: we need to remove one digit that is 1 or 4, to make thenu
    13 min read
  • Remove recurring digits in a given number
    Given a number as string, remove recurring digits from the given string. The changes must be made in-place. Expected time complexity O(n) and auxiliary space O(1).Examples: Input: num[] = "1299888833" Output: num[] = "12983" Input: num[] = "1299888833222" Output: num[] = "129832" We strongly recomme
    7 min read
  • Minimum number of digits required to be removed to make a number divisible by 4
    Given a number N, the task is to count the minimum number of digits to be removed from N to make it divisible by 4. Examples: Input: N = 12367Output: 1Explanation: Removing 7 from the number 1236 make the number divisible by 4. Therefore, the minimum count of digit to be removed is 1. Input: N = 243
    9 min read
  • Number of subsequences in a string divisible by n
    Given a string consisting of digits 0-9, count the number of subsequences in it divisible by m.Examples: Input : str = "1234", n = 4Output : 4The subsequences 4, 12, 24 and 124 are divisible by 4. Input : str = "330", n = 6Output : 4The subsequences 30, 30, 330 and 0 are divisible by n.Input : str =
    11 min read
  • Minimize count of alternating subsequences to divide given Binary String with subsequence number
    Given a binary string S of length N. The task is to find the following: The minimum number of subsequences, string S can be divided into, such that the subsequence does not contain adjacent zeroes or ones.Subsequence number to which each character of string S belongs. If there are many answers, outp
    11 min read
  • Minimum removal of subsequences of distinct consecutive characters required to empty a given string
    Given a binary string, str, the task is to empty the given string by minimum number of removals of a single character or a subsequence containing distinct consecutive characters from str. Examples: Input: str = "0100100111" Output: 3 Explanation: Removing the subsequence "010101" from the string mod
    6 min read
  • Given a number as a string, find the number of contiguous subsequences which recursively add up to 9
    Given a number as a string, write a function to find the number of substrings (or contiguous subsequences) of the given string which recursively add up to 9. Example: Digits of 729 recursively add to 9, 7 + 2 + 9 = 18 Recur for 18 1 + 8 = 9 Examples: Input: 4189 Output: 3 There are three substrings
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences