Problem
Given a string s
containing only digits, return the
lexicographically smallest string that can be obtained after swapping adjacent digits in s
with the same parity at most once.
Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.
Example 1:
Input: s = “45320”
Output: “43520”
Explanation:
s[1] == '5'
and s[2] == '3'
both have the same parity, and swapping them results in the lexicographically smallest string.
Example 2:
Input: s = “001”
Output: “001”
Explanation:
There is no need to perform a swap because s
is already the lexicographically smallest.
Constraints:
2 <= s.length <= 100
s
consists only of digits.
Solution
First attempt : Time complexity O(n)
/**
* @param {string} s
* @return {string}
*/
var getSmallestString = function(s) {
let smallestnumber = s;
let duplicate = s.split("");
if(s.length == 2){
//smallestnumber = s
if(s[0] % 2 == 0 && s[1] % 2 == 0){
let number = duplicate[0];
duplicate[0] = duplicate[1];
duplicate[1] = number;
if(duplicate.join("") < smallestnumber){
smallestnumber = duplicate.join("");
}
duplicate = s.split("");
}
else if(s[0] % 2 != 0 && s[1] % 2 != 0){
let number = duplicate[0];
duplicate[0] = duplicate[1];
duplicate[1] = number;
if(duplicate.join("") < smallestnumber){
smallestnumber = duplicate.join("");
}
duplicate = s.split("");
}
else{
return smallestnumber;
}
}
else{
for(let i = 0; i < s.length - 1; i++){
if(s[i] % 2 == 0 && s[i+1] % 2 == 0){
let number = duplicate[i];
duplicate[i] = duplicate[i+1];
duplicate[i+1] = number;
if(duplicate.join("") < smallestnumber){
smallestnumber = duplicate.join("");
}
duplicate = s.split("");
}
else if(s[i] % 2 != 0 && s[i+1] % 2 != 0){
let number = duplicate[i];
duplicate[i] = duplicate[i+1];
duplicate[i+1] = number;
if(duplicate.join("") < smallestnumber){
smallestnumber = duplicate.join("");
}
duplicate = s.split("");
}
}
}
return smallestnumber;
};
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.