C Program to Compare Two Strings Lexicographically
Here, we will build a C Program to compare two strings lexicographically. Given 2 strings s1 and s2, of lowercase English alphabets, denote the lexicographically greater string. Lexicographical order is the order in which words appear in the order of a dictionary.
s1 = "geeks", s2 = "geeksforgeeks
String 2 is lexicographically greater than string 1.
Sequence to follow these steps:
- Iterate over both the strings using a for-loop.
- Compare each character of the two strings till an unmatched character is found.
- For the unmatched character at position i, if s1[i] < s2[i], s1 is lexicographically smaller string.
- Otherwise, s2 is the lexicographically smaller string.
- If no unmatched character is found, compare the length of both strings.
- The longer string is lexicographically smaller.
String 1 is lexicographically greater than string 2.
- Time Complexity: O(N)
- Space complexity: O(1)
My Personal Notes arrow_drop_up
Please Login to comment...