Find the maximum number formed by swapping digits of same parity
Last Updated :
01 Jul, 2022
Given a number N, the task is to maximize this number by following the given conditions:
- The odd digit of the number can only be swapped by any odd digit present in the given number.
- The even digit of the number can only be swapped by any even digit present in the given number.
Examples:
Input: N = 234
Output: 432
Explanation: The 0th index is swapped with 2nd index.
Input: N = 6587
Output: 8765
Explanation: The 0th index is swapped with 2nd index.
The 1st index is swapped with 3rd index.
Naive approach: If a digit in the given number N is even then find the greatest element to its right which is also even and finally swap both. similarly do the same, if the digit is odd.
Follow the steps mentioned below to implement the idea:
- Convert the given number N into string s (This will make traversing on each digit of the number easy)
- Iterate the string from 0 to s.length()-1:
- Use variables to store the maximum value to the right of current index (say maxi) and its position (say idx).
- Iterate the string from j = i+1 to s.length()-1
- If both ith digit and jth digit is of the same parity and jth digit is greater than ith, then update the maxi and idx.
- Otherwise, continue the iteration.
- Finally swap s[i] with s[idx]
- Return the integer value of the string s.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to maximize the number
int maximizedNumber(int num)
{
// String will be used to represent the
// number in string
string s = to_string(num);
// Traversing the string
for (int i = 0; i < s.length(); i++) {
int maxi = s[i] - '0';
int idx = i;
// Check ith digit with all
// the remaining unoperated
// string to maximize the string
for (int j = i + 1; j < s.length();
j++) {
// If both the ith and
// jth digit is odd
if (maxi % 2 == 0
&& (s[j] - '0') % 2 == 0) {
// If the jth digit is
// greater than the ith digit
if (s[j] - '0' > maxi) {
maxi = s[j] - '0';
idx = j;
}
}
// If both ith and
// jth digit is even
else if (maxi % 2 == 1
&& (s[j] - '0') % 2 == 1) {
// If the jth digit is
// greater than ith digit.
if (s[j] - '0' > maxi) {
maxi = s[j] - '0';
idx = j;
}
}
}
// Swap the largest digit to the right
// of ith digit with ith digit
swap(s[i], s[idx]);
}
// Convert string into integer
return stoi(s);
}
// Driver code
int main()
{
int N = 6587;
// Function call
cout << maximizedNumber(N);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG {
static String swap(String str, int i, int j)
{
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i, str.charAt(j));
sb.setCharAt(j, str.charAt(i));
return sb.toString();
}
// Function to maximize the number
public static int maximizedNumber(int num)
{
// String will be used to represent the
// number in string
String s = Integer.toString(num);
// Traversing the string
for (int i = 0; i < s.length(); i++) {
int maxi = s.charAt(i) - '0';
int idx = i;
// Check ith digit with all
// the remaining unoperated
// string to maximize the string
for (int j = i + 1; j < s.length(); j++) {
// If both the ith and
// jth digit is odd
if (maxi % 2 == 0
&& (s.charAt(j) - '0') % 2 == 0) {
// If the jth digit is
// greater than the ith digit
if (s.charAt(j) - '0' > maxi) {
maxi = s.charAt(j) - '0';
idx = j;
}
}
// If both ith and
// jth digit is even
else if (maxi % 2 == 1
&& (s.charAt(j) - '0') % 2 == 1) {
// If the jth digit is
// greater than ith digit.
if (s.charAt(j) - '0' > maxi) {
maxi = s.charAt(j) - '0';
idx = j;
}
}
}
// Swap the largest digit to the right
// of ith digit with ith digit
s = swap(s, i, idx);
}
// Convert string into integer
return Integer.parseInt(s);
}
public static void main(String[] args)
{
int N = 6587;
// Function call
System.out.print(maximizedNumber(N));
}
}
// This code is contributed by Rohit Pradhan
Python3
# Python code to implement the approach
# Function to maximize the number
def maximizedNumber(num):
# Array String will be used to represent the
# number in string
s = list(str(num))
# Traversing the string
for i in range(len(s)):
maxi = int(s[i])
idx = i
# Check ith digit with all
# the remaining unoperated
# string to maximize the string
for j in range(i + 1,len(s)):
# If both the ith and
# jth digit is odd
if ((maxi % 2 == 0) and (int(s[j]) % 2 == 0)):
# If the jth digit is
# greater than the ith digit
if (int(s[j]) > maxi):
maxi = int(s[j])
idx = j
# If both ith and
# jth digit is even
elif ((maxi % 2 == 1) and (int(s[j]) % 2 == 1)):
# If the jth digit is
# greater than ith digit.
if (int(s[j]) > maxi):
maxi = int(s[j])
idx = j
# Swap the largest digit to the right
# of ith digit with ith digit
s[i],s[idx] = s[idx],s[i]
# Convert string into integer
return ''.join(s)
# Driver code
N = 6587
# Function call
print(maximizedNumber(N))
# This code is contributed by shinjanpatra
C#
// C# code to implement the approach
using System;
public class GFG
{
// Function to maximize the number
public static int maximizedNumber(int num)
{
// String will be used to represent the
// number in string
string s = num.ToString();
// Traversing the string
for (int i = 0; i < s.Length; i++) {
int maxi = s[i] - '0';
int idx = i;
// Check ith digit with all
// the remaining unoperated
// string to maximize the string
for (int j = i + 1; j < s.Length; j++) {
// If both the ith and
// jth digit is odd
if (maxi % 2 == 0
&& (s[j] - '0') % 2 == 0) {
// If the jth digit is
// greater than the ith digit
if (s[j] - '0' > maxi) {
maxi = s[j] - '0';
idx = j;
}
}
// If both ith and
// jth digit is even
else if (maxi % 2 == 1
&& (s[j] - '0') % 2 == 1) {
// If the jth digit is
// greater than ith digit.
if (s[j] - '0' > maxi) {
maxi = s[j] - '0';
idx = j;
}
}
}
// Swap the largest digit to the right
// of ith digit with ith digit
string swap = s.Substring(i, 1);
s = s.Remove(i, 1).Insert(i,
s.Substring(idx, 1));
s = s.Remove(idx, 1).Insert(idx, swap);
}
// Convert string into integer
return Int32.Parse(s);
}
public static void Main(string[] args)
{
int N = 6587;
// Function call
Console.WriteLine(maximizedNumber(N));
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript code to implement the approach
// Function to maximize the number
function maximizedNumber(num)
{
// Array String will be used to represent the
// number in string
var s = num.toString().split('');
// Traversing the string
for (var i = 0; i < s.length; i++) {
var maxi = parseInt(s[i]);
var idx = i;
// Check ith digit with all
// the remaining unoperated
// string to maximize the string
for (var j = i + 1; j < s.length;
j++) {
// If both the ith and
// jth digit is odd
if ((maxi % 2 == 0)
&& (parseInt(s[j]) % 2 == 0)) {
// If the jth digit is
// greater than the ith digit
if (parseInt(s[j]) > maxi) {
maxi = parseInt(s[j]);
idx = j;
}
}
// If both ith and
// jth digit is even
else if ((maxi % 2 == 1)
&& (parseInt(s[j])) % 2 == 1) {
// If the jth digit is
// greater than ith digit.
if (parseInt(s[j]) > maxi) {
maxi = parseInt(s[j]);
idx = j;
}
}
}
// Swap the largest digit to the right
// of ith digit with ith digit
var temp = s[i];
s[i] = s[idx];
s[idx] = temp;
}
// Convert string into integer
return (s.join(''));
}
// Driver code
var N = 6587;
// Function call
document.write(maximizedNumber(N));
// This code is contributed by phasing17
</script>
Time Complexity: O(N2), Where N is the length of the given string.
Auxiliary Space: O(N)
Efficient approach: This problem can be solved efficiently based on the following idea:
Store all even digits in non-increasing order and do the same for odd digits.
Now replace all stored even digits of given number in non-increasing order with even digits in it and do the same for odd digits.
Follow the steps mentioned below to implement the idea.
- Convert given number N into string s.
- Iterate over s and do the following:
- Store all even digits in a string (say evenDigit) and all odd digits in another string (say oddDigit).
- Sort both the strings in non-increasing order.
- Iterate over s and do the following:
- Use two iterators (say itr1 and itr2) to point to the next even or odd digit to be picked.
- If the digit in s is even, then replace it with the digit in evenDigit[itr1] and increment itr1.
- If the digit in s is odd, then replace it with the digit in oddDigit[itr2] and increment itr2.
- Finally, convert the string s into an integer and return it.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to maximize the number
int maximizedNumber(int num)
{
// Store all even digits
string oddDigit = "";
// Store all odd digits
string evenDigit = "";
// Convert given number into string
string s = to_string(num);
for (int i = 0; i < s.size(); i++) {
// Check if digit is even or odd
if ((s[i] - '0') % 2 == 0) {
evenDigit += s[i];
}
else {
oddDigit += s[i];
}
}
// Sort oddDigit and evenDigit string
// in non-increasing order.
sort(oddDigit.begin(), oddDigit.end(),
greater<int>());
sort(evenDigit.begin(), evenDigit.end(),
greater<int>());
int i1 = 0, j1 = 0;
for (int i = 0; i < s.size(); i++) {
// If the current digit is even
// then replace it with evenDigit[i1]
if ((s[i] - '0') % 2 == 0) {
s[i] = evenDigit[i1];
i1++;
}
// If the current digit is odd then
// replace it with the oddDigit[j1]
else {
s[i] = oddDigit[j1];
j1++;
}
}
return stoi(s);
}
// Driver code
int main()
{
int N = 6587;
// Function call
cout << maximizedNumber(N);
return 0;
}
Java
// Java code to implement the approach
import java.util.*;
// Helper class implementing Comparator interface
// to compare characters of a string in non
// increasing order
class charSort implements Comparator<Character> {
@Override public int compare(Character c1, Character c2)
{
// Ignoring case
return Character.compare(Character.toLowerCase(c2),
Character.toLowerCase(c1));
}
};
class GFG {
// Function to maximize the number
static int maximizedNumber(int num)
{
// Store all even digits
ArrayList<Character> oddDigit
= new ArrayList<Character>();
// Store all odd digits
ArrayList<Character> evenDigit
= new ArrayList<Character>();
// Convert given number into char array
char[] s = (String.valueOf(num)).toCharArray();
for (int i = 0; i < s.length; i++) {
// Check if digit is even or odd
if ((s[i] - '0') % 2 == 0) {
evenDigit.add(s[i]);
}
else {
oddDigit.add(s[i]);
}
}
// Sort oddDigit and evenDigit string
// in non-increasing order.
oddDigit.sort(new charSort());
evenDigit.sort(new charSort());
int i1 = 0, j1 = 0;
for (int i = 0; i < s.length; i++) {
// If the current digit is even
// then replace it with evenDigit[i1]
if ((s[i] - '0') % 2 == 0) {
s[i] = evenDigit.get(i1);
i1++;
}
// If the current digit is odd then
// replace it with the oddDigit[j1]
else {
s[i] = oddDigit.get(j1);
j1++;
}
}
return Integer.parseInt(new String(s));
}
// Driver Code
public static void main(String[] args)
{
int N = 6587;
// Function call
System.out.println(maximizedNumber(N));
}
}
// This code is contributed by phasing17
Python3
# Python3 code to implement the approach
# Function to maximize the number
def maximizedNumber(num):
# Store all even digits
oddDigit = "";
# Store all odd digits
evenDigit = "";
# Convert given number into string
s = list(str(num))
for i in range(len(s)):
# Check if digit is even or odd
if (int(s[i]) % 2 == 0):
evenDigit += s[i];
else:
oddDigit += s[i];
oddDigit = list(oddDigit)
evenDigit = list(evenDigit)
# Sort oddDigit and evenDigit string
# in non-increasing order.
oddDigit.sort();
oddDigit.reverse();
evenDigit.sort();
evenDigit.reverse();
i1 = 0;
j1 = 0;
for i in range(len(s)):
# If the current digit is even
# then replace it with evenDigit[i1]
if (int(s[i]) % 2 == 0):
s[i] = evenDigit[i1];
i1 += 1
# If the current digit is odd then
# replace it with the oddDigit[j1]
else :
s[i] = oddDigit[j1];
j1 += 1
return "".join(s)
# Driver code
N = 6587;
#Function call
print(maximizedNumber(N));
# This code is contributed by phasing17
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
// Helper class implementing Comparator interface
// to compare characters of a string in non
// increasing order
class charSort : Comparer<char> {
public override int Compare(char c1, char c2)
{
// Ignoring case
return (Char.ToLower(c2))
.CompareTo(Char.ToLower(c1));
}
};
class GFG {
// Function to maximize the number
static int maximizedNumber(int num)
{
// Store all even digits
List<char> oddDigit = new List<char>();
// Store all odd digits
List<char> evenDigit = new List<char>();
// Convert given number into char array
char[] s = (num.ToString()).ToCharArray();
for (int i = 0; i < s.Length; i++) {
// Check if digit is even or odd
if ((s[i] - '0') % 2 == 0) {
evenDigit.Add(s[i]);
}
else {
oddDigit.Add(s[i]);
}
}
// Sort oddDigit and evenDigit string
// in non-increasing order.
oddDigit.Sort(new charSort());
evenDigit.Sort(new charSort());
int i1 = 0, j1 = 0;
for (int i = 0; i < s.Length; i++) {
// If the current digit is even
// then replace it with evenDigit[i1]
if ((s[i] - '0') % 2 == 0) {
s[i] = evenDigit[i1];
i1++;
}
// If the current digit is odd then
// replace it with the oddDigit[j1]
else {
s[i] = oddDigit[j1];
j1++;
}
}
return int.Parse(s);
}
// Driver Code
public static void Main(string[] args)
{
int N = 6587;
// Function call
Console.WriteLine(maximizedNumber(N));
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript code to implement the approach
// Function to maximize the number
function maximizedNumber(num)
{
// Store all even digits
var oddDigit = "";
// Store all odd digits
var evenDigit = "";
// Convert given number into string
var s = num.toString().split("");
for (var i = 0; i < s.length; i++) {
// Check if digit is even or odd
if (parseInt(s[i]) % 2 == 0) {
evenDigit += s[i];
}
else {
oddDigit += s[i];
}
}
oddDigit = oddDigit.split("");
evenDigit = evenDigit.split("");
// Sort oddDigit and evenDigit string
// in non-increasing order.
oddDigit.sort();
oddDigit.reverse();
evenDigit.sort();
evenDigit.reverse();
var i1 = 0;
var j1 = 0;
for (var i = 0; i < s.length; i++) {
// If the current digit is even
// then replace it with evenDigit[i1]
if (parseInt(s[i]) % 2 == 0) {
s[i] = evenDigit[i1];
i1++;
}
// If the current digit is odd then
// replace it with the oddDigit[j1]
else {
s[i] = oddDigit[j1];
j1++;
}
}
return s.join("");
}
// Driver code
var N = 6587;
// Function call
document.write(maximizedNumber(N));
// This code is contributed by phasing17
</script>
Time Complexity: O(M * log M), Where M is the number of digits present in N.
Auxiliary Space: O(M)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem