

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find Lexicographically Smallest String With One Swap in Python
Suppose we have a string s, we have to find the lexicographically smallest string that can be made if we can make at most one swap between two characters in the given string s.
So, if the input is like "zyzx", then the output will be "xyzz"
To solve this, we will follow these steps −
- temp := an array of size s and fill with 0
- m:= size of s - 1
- for i in range size of s -1 to -1, decrease by 1, do
- if s[i] < s[m], then
- m := i
- temp[i] := m
- for i in range 0 to size of s, do
- a := temp[i]
- if s[a] is not same as s[i], then
- return substring of s [from index 0 to i] concatenate s[a] concatenate substring of s [from index i+1 to a] concatenate s[i] concatenate substring of s [from index a+1 to end]
- if s[i] < s[m], then
- return s
Example
class Solution: def solve(self, s): temp = [0]*len(s) m=len(s)-1 for i in range(len(s)-1, -1, -1): if s[i]<s[m]: m=i temp[i] = m for i in range(len(s)): a = temp[i] if s[a] != s[i]: return s[:i]+s[a]+s[i+1:a]+s[i]+s[a+1:] return s ob = Solution() print(ob.solve("zyzx"))
Input
zyzx
Output
xyzz
- Related Questions & Answers
- Program to find kth smallest n length lexicographically smallest string in python
- Program to find lexicographically smallest non-palindromic string in Python
- Program to find lexicographically smallest string after applying operations in Python
- Program to find lexicographically smallest string to move from start to destination in Python
- Program to find lexicographically smallest subsequence of size k in Python
- Program to find lexicographically smallest lowercase string of length k and distance n in Python
- Lexicographically Smallest Equivalent String in C++
- Find the lexicographically smallest string which satisfies the given condition in Python
- Program to find smallest string with a given numeric value in Python
- Previous Permutation With One Swap in Python
- Program to find lexicographically largest mountain list in Python
- Program to swap string characters pairwise in Python
- Queries to answer the X-th smallest sub-string lexicographically in C++
- Program to check whether one string swap can make strings equal or not using Python
- Form the smallest number using at most one swap operation in C++
Advertisements