Maximum number that can be obtain by swapping adjacent digits of same parity
Last Updated :
20 Mar, 2024
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)
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)
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read