Smallest number possible by swapping adjacent even odd pairs
Last Updated :
30 Mar, 2022
Given a numeric string str, the task is to find the smallest integer that can be formed by swapping adjacent digits of distinct parity. Examples:
Input: 836360 Output: 338660 Explanation: 1st Swap: 836360 -> 386360 2nd Swap: 386360 -> 383660 3rd Swap: 383660 -> 338660 Input: 1003 Output: 13
Approach: We can observe that on repeated swaps, we can split the even and odd digits of str into two separate blocks. The order of digits in their respective blocks will be the same as their order of appearance in the string as swapping within a block (same parity) is not allowed. Thus, after separating str into two separate blocks, we need to traverse these two blocks and append the minimum of the two values currently pointed, to the answer. The final string generated after this operation followed by the removal of leading 0's, if any, is the required answer. Example: The even and odd blocks int the order of their appearance in 836360 are {8, 6, 6, 0} and {3, 3} respectively. Hence the smallest number ans formed is as follows:
- ans = ans + min(8, 3) => ans = 3
- ans = ans + min(8, 3) => ans = 33
- Since, all the odd digits are exhausted, the remaining even digits need to be added one by one.
- Hence, the required answer is 338660
Below is the implementation of the above approach:
C++
// C++ Program to find the
// smallest number possible
// by swapping adjacent digits
// of different parity
#include <bits/stdc++.h>
using namespace std;
// Function to return the
// smallest number possible
string findAns(string s)
{
int digit;
// Arrays to store odd and
// even digits in the order
// of their appearance in
// the given string
vector<int> odd;
vector<int> even;
// Insert the odd and
// even digits
for (auto c : s) {
digit = c - '0';
if (digit & 1)
odd.push_back(digit);
else
even.push_back(digit);
}
// pointer to odd digit
int i = 0;
// pointer to even digit
int j = 0;
string ans = "";
while (i < odd.size()
and j < even.size()) {
if (odd[i] < even[j])
ans += (char)(odd[i++] + '0');
else
ans += (char)(even[j++] + '0');
}
// In case number of even and
// odd digits are not equal
// If odd digits are remaining
while (i < odd.size())
ans += (char)(odd[i++] + '0');
// If even digits are remaining
while (j < even.size())
ans += (char)(even[j++] + '0');
// Removal of leading 0's
while (ans[0] == '0') {
ans.erase(ans.begin());
}
return ans;
}
int main()
{
string s = "894687536";
cout << findAns(s);
return 0;
}
Java
// Java program to find the smallest
// number possible by swapping adjacent
// digits of different parity
import java.util.*;
class GFG{
// Function to return the
// smallest number possible
static String findAns(String s)
{
int digit;
// Arrays to store odd and even
// digits in the order their
// appearance in the given String
Vector<Integer> odd =new Vector<Integer>();
Vector<Integer> even = new Vector<Integer>();
// Insert the odd and
// even digits
for(char c : s.toCharArray())
{
digit = c - '0';
if (digit % 2 == 1)
odd.add(digit);
else
even.add(digit);
}
// Pointer to odd digit
int i = 0;
// Pointer to even digit
int j = 0;
String ans = "";
while (i < odd.size() && j < even.size())
{
if (odd.get(i) < even.get(j))
ans += (char)(odd.get(i++) + '0');
else
ans += (char)(even.get(j++) + '0');
}
// In case number of even and
// odd digits are not equal
// If odd digits are remaining
while (i < odd.size())
ans += (char)(odd.get(i++) + '0');
// If even digits are remaining
while (j < even.size())
ans += (char)(even.get(j++) + '0');
// Removal of leading 0's
while (ans.charAt(0) == '0')
{
ans = ans.substring(1);
}
return ans;
}
// Driver code
public static void main(String[] args)
{
String s = "894687536";
System.out.print(findAns(s));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 Program to find the
# smallest number possible
# by swapping adjacent digits
# of different parity
# Function to return the
# smallest number possible
def findAns(s):
# Arrays to store odd and
# even digits in the order
# of their appearance in
# the given string
odd = []
even = []
# Insert the odd and
# even digits
for c in s:
digit = int(c)
if (digit & 1):
odd.append(digit)
else:
even.append(digit)
# pointer to odd digit
i = 0
# pointer to even digit
j = 0
ans = ""
while (i < len(odd) and j < len(even)):
if (odd[i] < even[j]):
ans += str(odd[i])
i = i + 1
else:
ans += str(even[j])
j = j + 1
# In case number of even and
# odd digits are not equal
# If odd digits are remaining
while (i < len(odd)):
ans += str(odd[i])
i = i + 1
# If even digits are remaining
while (j < len(even)):
ans += str(even[j])
j = j + 1
# Removal of leading 0's
while (ans[0] == '0'):
ans = ans[1:]
return ans
# Driver Code
s = "894687536"
print(findAns(s))
# This code is contributed by yatin
C#
// C# program to find the smallest
// number possible by swapping adjacent
// digits of different parity
using System;
using System.Collections.Generic;
class GFG{
// Function to return the
// smallest number possible
static String findAns(String s)
{
int digit;
// Arrays to store odd and even
// digits in the order their
// appearance in the given String
List<int> odd = new List<int>();
List<int> even = new List<int>();
// Insert the odd and
// even digits
foreach(char c in s.ToCharArray())
{
digit = c - '0';
if (digit % 2 == 1)
odd.Add(digit);
else
even.Add(digit);
}
// Pointer to odd digit
int i = 0;
// Pointer to even digit
int j = 0;
String ans = "";
while (i < odd.Count && j < even.Count)
{
if (odd[i] < even[j])
ans += (char)(odd[i++] + '0');
else
ans += (char)(even[j++] + '0');
}
// In case number of even and
// odd digits are not equal
// If odd digits are remaining
while (i < odd.Count)
ans += (char)(odd[i++] + '0');
// If even digits are remaining
while (j < even.Count)
ans += (char)(even[j++] + '0');
// Removal of leading 0's
while (ans[0] == '0')
{
ans = ans.Substring(1);
}
return ans;
}
// Driver code
public static void Main(String[] args)
{
String s = "894687536";
Console.Write(findAns(s));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// javascript program to find the smallest
// number possible by swapping adjacent
// digits of different parity
// Function to return the
// smallest number possible
function findAns( s) {
var digit;
// Arrays to store odd and even
// digits in the order their
// appearance in the given String
var odd = [];
var even = [];
// Insert the odd and
// even digits
for (var i =0;i<s.length;i++) {
digit = s[i].charCodeAt(0) -'0'.charCodeAt(0);
if (digit % 2 == 1)
odd.push(digit);
else
even.push(digit);
}
// Pointer to odd digit
var i = 0;
// Pointer to even digit
var j = 0;
var ans = "";
while (i < odd.length && j < even.length) {
if (odd[i] < even[j])
ans += String.fromCharCode(odd[i++] + '0'.charCodeAt(0));
else
ans += String.fromCharCode(even[j++] + '0'.charCodeAt(0));
}
// In case number of even and
// odd digits are not equal
// If odd digits are remaining
while (i < odd.length)
ans += String.fromCharCode(odd[i++] + '0'.charCodeAt(0));
// If even digits are remaining
while (j < even.length)
ans += String.fromCharCode(even[j++] + '0'.charCodeAt(0));
// Removal of leading 0's
while (ans.charAt(0) == '0') {
ans = ans.substring(1);
}
return ans;
}
// Driver code
var s = "894687536";
document.write(findAns(s));
// This code is contributed by gauravrajput1
</script>
Time Complexity: O(N), where N is the size of the given string.
Similar Reads
Maximum number that can be obtain by swapping adjacent digits of same parity 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 =
13 min read
Minimize moves to segregate even and odd by swapping adjacent elements Given an array arr[] of size N, the task is to find the minimum moves to segregate even and odd numbers by swapping two adjacent elements at a time. Example: Input: N = 7, arr = {3, 5, 2, 7, 9, 11, 12}Output: 3Explanation: Swap arr[2] and arr[3] to get arr = {3, 5, 7, 2, 9, 11, 12}.Move 2: Swap arr[
5 min read
Convert Array such that no two even or odd numbers are adjacent Given an array arr[], the task is to print the minimum number of operations required to convert the array such that neither two even elements are adjacent nor two odd numbers are adjacent. In other words arr[i]%2 != arr[i+1]%2. For that, you can perform certain operations. (consider 0-based indexing
9 min read
Lexicographically largest Array by swapping adjacent with even sum You are given an array arr[] of size N. You can swap two adjacent elements of the array if their sum is even. The task is to find the lexicographically largest possible array that can be generated by performing this operation any number of times. Examples: Input: N = 3, arr[] = {1, 3, 5}Output: {5,
4 min read
Minimize the count of adjacent pairs with different parity Given an array arr of size N containing some integers from the range [1, N] and -1 in the remaining indices, the task is to replace -1 by the remaining integers from [1, N] such that the count of pairs of adjacent elements with different parity is minimized. Examples: Input: arr = {-1, 5, -1, 2, 3}
10 min read
Minimize given Number by swapping adjacent digits with odd difference Given a string S of length N representing an integer that consists of only characters '1', '2' and '3', the task is to find the smallest number that can be formed from the string by swapping the adjacent characters if their absolute difference is odd any number of times. Examples: Input: S = "213123
9 min read
Check if Array can be sorted by swapping adjacent elements having odd sum Given an array arr[], the task is to check if the array can be sorted using the given operation any number of times. In one operation, you can swap any two adjacent elements if their sum is odd. Examples: Input: arr[] = [1, 6, 31, 14]Output: YesExplanation: Swap 31 and 14 (31 + 14 = 45 which is odd)
7 min read
Largest even number possible by using one swap operation in given number Given an odd number in the form of a string, the task is to make the largest even number from the given number, and you are allowed to do only one swap operation. Examples : Input: 1235785Output: 1535782Explanation: Swap 2 and 5. Input: 536425Output: 536524Explanation: Swap 4 and 5 to make the large
6 min read
Smallest array that can be obtained by replacing adjacent pairs with their products Given an array arr[] of size N, the task is to print the least possible size the given array can be reduced to by performing the following operations: Remove any two adjacent elements, say arr[i] and arr[i+1] and insert a single element arr[i] * arr[i+1] at that position in the array.If all array el
4 min read