Open In App

Maximum number that can be obtain by swapping adjacent digits of same parity

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, the task is to find the maximum integer that can be obtained from the given integer such that the adjacent digits of the same parity can be swapped any number of times. Two digits of the same parity mean they will have the same remainder when divided by two.

Examples:

Input: S = 468136
Output: 864316
Explanation: The operations are performed as:

  • Initially: S = 468136
  • First Operation: 6 and 8 are adjacent and their parity is also the same, Therefore, after swapping them, S = 486136
  • Second Operation: 4 and 8 are adjacent and their parity is also the same. After swapping them, S = 846136
  • Third Operation: 1 and 3 are adjacent and their parity is also same. After swapping them, S = 846316
  • Fourth Operation: 4 and 6 are adjacent and their parity is also the same. After swapping them, S = 864316

It can be verified that it is the maximum possible number that can be obtained using a given operation.

Input: S = 97876324234234
Output: 97876342234234
Explanation: It can be verified that using the given operation, 97876342234234 is the maximum number that can be obtained.

Approach: To solve the problem follow the below idea

The problem is based on the Two Pointer and Sorting. Find out each window of consecutive digits having same parity using Two Pointer Technique. Then reverse every window of digits into descending order using sorting and merge the digits of all windows. By this approach, we can solve the problem easily.

Steps taken to solve the problem:

  • Create an array let’s say Digits[] and store the digits of S in this array.
  • Create an ArrayList of ArrayList<ArrayList<Integer>> data type let’s say List stores the window of same parity elements.
  • Apply two-pointer technique to find the window of consecutive elements having same parity. Additionally, store those elements into an ArrayList let say Temp and sort Temp into Descending order using Collections.reverseOrder(). After that insert Temp into List.
  • Output all the elements in serial manner stored in List.

Implementation of the above approach:

C++
//code contributed by flutterfly
#include <iostream>
#include <vector>
#include <algorithm>

// Method to print maximum possible number
void MaxNumber(std::string str) {
    // N stores the length of String
    int N = str.length();

    // Array to store digits of String
    std::vector<int> digits(N);

    // Loop for initializing digits of String into
    // digits[]
    for (int i = 0; i < N; i++) {
        digits[i] = (std::stoi(std::string(1, str[i])));
    }

    // Vector of vectors to store consecutive windows of same
    // parity
    std::vector<std::vector<int>> list;

    // Left End of the window
    int left = 0;

    // Two pointer algorithm to find window of same
    // parity consecutive elements
    while (left < N) {

        // Right end of window
        int right = left;

        // Temporary vector to store the window
        std::vector<int> temp;

        // Incrementing right End to find the window of
        // same parity elements
        while (right < (N - 1)
               && (digits[right]) % 2
                   == (digits[right + 1]) % 2) {

            // Adding elements into temp vector
            temp.push_back(digits[right]);
            right++;
        }

        // Adding the last element of the window
        temp.push_back(digits[right]);

        // Sorting temp in reverse order
        std::sort(temp.rbegin(), temp.rend());

        // Adding temp into list
        list.push_back(temp);

        // Left End of next window
        left = right + 1;
    }

    // Printing the elements from the list
    for (const auto &l : list) {
        for (int x : l) {
            std::cout << x;
        }
    }
}

// Driver Function
int main() {
    // Input String
    std::string str = "468136";

    // Function call
    MaxNumber(str);

    return 0;
}
Java
import java.util.*;

// Driver Class
public class GFG {

    // Driver Function
    public static void main(String[] args)
    {
        // Input String
        String str = "468136";

        // Function call
        Max_number(str);
    }

    // Method to print maximum possible number
    public static void Max_number(String str)
    {

        // N stores the length of String
        int N = str.length();

        // Array to store digits of String
        int[] digits = new int[N];

        // Loop for initializing digits of String into
        // digits[]
        for (int i = 0; i < N; i++) {
            digits[i]
                = (Integer.parseInt("" + str.charAt(i)));
        }

        // ArrayList to store consecutive windows of same
        // parity
        ArrayList<ArrayList<Integer>> list
            = new ArrayList<>();

        // Left End of the window
        int left = 0;

        // Two pointer algorithm to find window of same
        // parity consecutive elements
        while (left < N) {

            // Right end of window
            int right = left;

            // temporary ArrayList to store the window
            ArrayList<Integer> temp = new ArrayList<>();

            // Incrementing right End to find the window of
            // same parity elements
            while (right < (N - 1)
                   && (digits[right]) % 2
                          == (digits[right + 1]) % 2) {

                // Adding elements into temp ArrayList
                temp.add(digits[right]);
                right++;
            }

            // Adding the last element of the window
            temp.add(digits[right]);

            // Sorting temp into reverse order using inbuilt
            // Collections class
            Collections.sort(temp, Collections.reverseOrder());

            // Adding temp into list
            list.add(temp);

            // left End of next window
            left = right + 1;
        }

        // Printing the elements from the list
        for (ArrayList<Integer> l : list) {
            for (Integer x : l) {
                System.out.print(x);
            }
        }
    }
}
C#
//code contributed by flutterfly
using System;
using System.Collections.Generic;
using System.Linq;

// Driver Class
public class GFG
{
    // Driver Function
    public static void Main()
    {
        // Input String
        string str = "468136";

        // Function call
        MaxNumber(str);
    }

    // Method to print maximum possible number
    public static void MaxNumber(string str)
    {
        // N stores the length of String
        int N = str.Length;

        // Array to store digits of String
        int[] digits = new int[N];

        // Loop for initializing digits of String into
        // digits[]
        for (int i = 0; i < N; i++)
        {
            digits[i] = int.Parse(str[i].ToString());
        }

        // List to store consecutive windows of same
        // parity
        List<List<int>> list = new List<List<int>>();

        // Left End of the window
        int left = 0;

        // Two pointer algorithm to find window of same
        // parity consecutive elements
        while (left < N)
        {
            // Right end of window
            int right = left;

            // Temporary List to store the window
            List<int> temp = new List<int>();

            // Incrementing right End to find the window of
            // same parity elements
            while (right < (N - 1) && (digits[right]) % 2 == (digits[right + 1]) % 2)
            {
                // Adding elements into temp List
                temp.Add(digits[right]);
                right++;
            }

            // Adding the last element of the window
            temp.Add(digits[right]);

            // Sorting temp in reverse order
            temp.Sort((a, b) => b.CompareTo(a));

            // Adding temp into list
            list.Add(temp);

            // Left End of next window
            left = right + 1;
        }

        // Printing the elements from the list
        foreach (var l in list)
        {
            foreach (var x in l)
            {
                Console.Write(x);
            }
        }
    }
}
Javascript
//code contributed by flutterfly
// Driver Class
class GFG {

    // Driver Function
    static main() {
        // Input String
        let str = "468136";

        // Function call
        GFG.maxNumber(str);
    }

    // Method to print maximum possible number
    static maxNumber(str) {
        // N stores the length of String
        let N = str.length;

        // Array to store digits of String
        let digits = Array.from(str, ch => parseInt(ch));

        // Array to store consecutive windows of same
        // parity
        let list = [];

        // Left End of the window
        let left = 0;

        // Two-pointer algorithm to find a window of the same
        // parity consecutive elements
        while (left < N) {

            // Right end of the window
            let right = left;

            // Temporary Array to store the window
            let temp = [];

            // Incrementing right End to find the window of
            // the same parity elements
            while (right < (N - 1) && (digits[right] % 2) === (digits[right + 1] % 2)) {

                // Adding elements into the temp Array
                temp.push(digits[right]);
                right++;
            }

            // Adding the last element of the window
            temp.push(digits[right]);

            // Sorting temp in reverse order
            temp.sort((a, b) => b - a);

            // Adding temp into the list
            list.push(temp);

            // Left End of the next window
            left = right + 1;
        }

        // Printing the elements from the list
        for (let l of list) {
            for (let x of l) {
                process.stdout.write(x.toString());
            }
        }
    }
}

// Call the main function if this script is run
GFG.main();
Python3
# code by flutterfly
from __future__ import print_function  # This line is needed for Python 2 to use the print function

def max_number(s):
    # N stores the length of String
    N = len(s)

    # List to store digits of String
    digits = [int(ch) for ch in s]

    # List to store consecutive windows of the same parity
    window_list = []

    # Left End of the window
    left = 0

    # Two-pointer algorithm to find a window of the same
    # parity consecutive elements
    while left < N:
        # Right end of the window
        right = left

        # Temporary list to store the window
        temp = []

        # Incrementing right End to find the window of
        # the same parity elements
        while right < (N - 1) and (digits[right] % 2) == (digits[right + 1] % 2):
            # Adding elements into temp list
            temp.append(digits[right])
            right += 1

        # Adding the last element of the window
        temp.append(digits[right])

        # Sorting temp in reverse order
        temp.sort(reverse=True)

        # Adding temp into the list
        window_list.append(temp)

        # Left End of the next window
        left = right + 1

    # Printing the elements from the list without spaces
    for l in window_list:
        for x in l:
            print(x, end="")
    print()  # Add a new line at the end

# Driver Function
if __name__ == "__main__":
    # Input String
    input_str = "468136"

    # Function call
    max_number(input_str)

Output
864316


Time Complexity: O(N*logN), As sorting is performed
Auxiliary Space: O(N), As ArrayList<ArrayList<Integer>> and Digits[] are used.

Approach 2:

The above approach can be further optimized by observing that digits can only be from 0 to 9, hence using count sort would be more efficient.

Steps taken to optimize:

While essentially using the same approach as above, we are going to introduce a simple frequency array to store the frequency of each character in the window as it occurs, and when there is a difference in parity we’ll be storing each value in our answer in reverse order making use of the count sort method.

Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Method to print maximum possible number
void MaxNumber(string str) {
    // N stores the length of String
    int N = str.length();

    //string ans to store the answer
    string ans = "";
  
      // freq array to store frequency of elements in window
    vector<int> freq(10);

    // Left End of the window
    int left = 0;

    // Two pointer algorithm to find window of same
    // parity consecutive elements
    while (left < N) {
      
        // Right end of window
        int right = left;

        // Incrementing right End to find the window of
        // same parity elements
        while (right < (N - 1)
               && (str[right] - '0') % 2
                   == (str[right + 1] - '0') % 2) {

            // Adding elements into freq vector
              ++freq[str[right] - '0'];
            right++;
        }

        // Adding the last element of the window
        ++freq[str[right] - '0'];

        // Adding elements into list
        for(int i = 9 ; i >= 0 ; i--){
          while(freq[i] > 0){
            ans += to_string(i);
            --freq[i];
          }
        }
            
        // Left End of next window
        left = right + 1;
    }

    // Printing the answer
    cout << ans << "\n";
}

// Driver Function
int main() {
    // Input String
    string str = "468136";

    // Function call
    MaxNumber(str);

    return 0;
}
Java
//Code contributed by adicruelking and flutterfly

import java.util.Arrays;

public class Main {
    // Method to print maximum possible number
    static void maxNumber(String str) {
      
        // N stores the length of String
        int N = str.length();

        // String ans to store the answer
        StringBuilder ans = new StringBuilder();

        // Array to store digits of String
        int[] digits = new int[N];

        // Loop for initializing digits of String into digits[]
        for (int i = 0; i < N; i++) {
            digits[i] = Character.getNumericValue(str.charAt(i));
        }

        // Left End of the window
        int left = 0;

        // Two pointer algorithm to find window of same
        // parity consecutive elements
        while (left < N) {
            // freq array to store frequency of elements in window
            int[] freq = new int[10];

            // Right end of window
            int right = left;

            // Incrementing right End to find the window of
            // same parity elements
            while (right < (N - 1) && (digits[right] % 2) == (digits[right + 1] % 2)) {
                // Adding elements into freq array
                ++freq[digits[right]];
                right++;
            }

            // Adding the last element of the window
            ++freq[digits[right]];

            // Adding elements into list
            for (int i = 9; i >= 0; i--) {
                while (freq[i] > 0) {
                    ans.append(i);
                    --freq[i];
                }
            }

            // Left End of next window
            left = right + 1;
        }

        // Printing the answer
        System.out.println(ans);
    }

    // Driver Function
    public static void main(String[] args) {
        // Input String
        String str = "468136";

        // Function call
        maxNumber(str);
    }
}
JavaScript
function maxNumber(s) {
    // N stores the length of String
    let n = s.length;

    // string ans to store the answer
    let ans = "";

    // freq array to store frequency of elements in window
    let freq = Array(10).fill(0);

    // Left End of the window
    let left = 0;

    // Two pointer algorithm to find window of same
    // parity consecutive elements
    while (left < n) {
        // Right end of window
        let right = left;

        // Incrementing right End to find the window of
        // same parity elements
        while (right < n - 1 && parseInt(s[right]) % 2 === parseInt(s[right + 1]) % 2) {
            // Adding elements into freq array
            freq[parseInt(s[right])] += 1;
            right += 1;
        }

        // Adding the last element of the window
        freq[parseInt(s[right])] += 1;

        // Adding elements into list
        for (let i = 9; i >= 0; i--) {
            while (freq[i] > 0) {
                ans += String(i);
                freq[i] -= 1;
            }
        }

        // Left End of next window
        left = right + 1;
    }

    // Printing the answer
    console.log(ans);
}

// Driver Function
let input_str = "468136";
// Function call
maxNumber(input_str);
Python3
# Method to print maximum possible number
def max_number(s):
    # N stores the length of String
    n = len(s)

    # string ans to store the answer
    ans = ""

    # freq list to store frequency of elements in window
    freq = [0] * 10

    # Left End of the window
    left = 0

    # Two pointer algorithm to find window of same
    # parity consecutive elements
    while left < n:
        # Right end of window
        right = left

        # Incrementing right End to find the window of
        # same parity elements
        while right < n - 1 and int(s[right]) % 2 == int(s[right + 1]) % 2:
            # Adding elements into freq vector
            freq[int(s[right])] += 1
            right += 1

        # Adding the last element of the window
        freq[int(s[right])] += 1

        # Adding elements into list
        for i in range(9, -1, -1):
            while freq[i] > 0:
                ans += str(i)
                freq[i] -= 1

        # Left End of next window
        left = right + 1

    # Printing the answer
    print(ans)

# Driver Function
if __name__ == "__main__":
    # Input String
    input_str = "468136"

    # Function call
    max_number(input_str)

Output
864316

Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads