Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check if the characters of a given string are in alphabetical order in Python
Suppose we have a string s. We have to check whether characters in s are in alphabetical order or not.
So, if the input is like s = "mnnooop", then the output will be True.
Method 1: Using Sorting Approach
To solve this, we will follow these steps ?
- char_arr := a new list from the characters present in s
- sort the list char_arr
- return char_arr is same as list of all characters in s then true otherwise false
Example
def solve(s):
char_arr = list(s)
char_arr.sort()
return char_arr == list(s)
s = "mnnooop"
print(solve(s))
The output of the above code is ?
True
Method 2: Using Direct Comparison
A more efficient approach is to directly compare the string with its sorted version ?
def is_alphabetical_order(s):
return s == ''.join(sorted(s))
# Test with multiple examples
strings = ["mnnooop", "hello", "abc", "dcba"]
for string in strings:
result = is_alphabetical_order(string)
print(f"'{string}' is in alphabetical order: {result}")
The output of the above code is ?
'mnnooop' is in alphabetical order: True 'hello' is in alphabetical order: False 'abc' is in alphabetical order: True 'dcba' is in alphabetical order: False
Method 3: Using Loop Comparison
We can also check by comparing adjacent characters without sorting ?
def check_alphabetical_loop(s):
for i in range(len(s) - 1):
if s[i] > s[i + 1]:
return False
return True
# Test the function
test_string = "mnnooop"
print(f"'{test_string}' is in alphabetical order: {check_alphabetical_loop(test_string)}")
test_string2 = "hello"
print(f"'{test_string2}' is in alphabetical order: {check_alphabetical_loop(test_string2)}")
The output of the above code is ?
'mnnooop' is in alphabetical order: True 'hello' is in alphabetical order: False
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Sorting | O(n log n) | O(n) | Simple implementation |
| Direct Comparison | O(n log n) | O(n) | Most readable |
| Loop Comparison | O(n) | O(1) | Best performance |
Conclusion
Use the loop comparison method for optimal performance with O(n) time complexity. The sorting approaches are simpler to understand but less efficient for large strings.
Advertisements
