
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find String in Lexicographic Order Between Two Strings in Python
Suppose we have two strings S and T, we have to check whether a string of the same length which is lexicographically bigger than S and smaller than T. We have to return -1 if no such string is available. We have to keep in mind that S = S1S2… Sn is termed to be lexicographically less than T = T1T2… Tn, provided there exists an i, so that S1= T1, S2= T2, … Si – 1= Ti – 1, Si < Ti.
So, if the input is like S = "bbb" and T = "ddd", then the output will be "bbc"
To solve this, we will follow these steps −
- n := size of string
- for i in range n - 1 to 0, decrease by 1, do
- if string[i] is not same as 'z', then
- k := ASCII of (string[i])
- string[i] := character from ASCII (k + 1)
- join string characters and return
- string[i] := 'a'
- if string[i] is not same as 'z', then
Example
Let us see the following implementation to get better understanding −
def find_next(string): n = len(string) for i in range(n - 1, -1, -1): if string[i] != 'z': k = ord(string[i]) string[i] = chr(k + 1) return ''.join(string) string[i] = 'a' S = "bbb" T = "ddd" S = list(S) res = find_next(S) if res != T: print(res) else: print(-1)
Input
"bbb", "ddd"
Output
bbc
Advertisements