Lexicographically Less Than in Strings

The term “lexicographically less than” is used to compare two strings based on the ASCII values of their characters. The comparison starts from the first character of each string. If the first characters are the same, the comparison moves on to the next characters, and so on. A string is considered lexicographically smaller if its first differing character has a smaller ASCII value than the corresponding character in the other string. If one string is a prefix of another, the shorter string is considered smaller.

Java Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class LexicographicComparison {
    public static boolean isLexicographicallySmaller(String str1, String str2) {
        int length1 = str1.length();
        int length2 = str2.length();
        int minLength = Math.min(length1, length2);

        for (int i = 0; i < minLength; i++) {
            if (str1.charAt(i) < str2.charAt(i)) {
                return true;
            } else if (str1.charAt(i) > str2.charAt(i)) {
                return false;
            }
        }

        return length1 < length2;
    }
}

In Java, we use charAt() to access individual characters for comparison. If all characters are the same up to the shortest string’s length, the shorter string is considered smaller.

C++ Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <string>

bool isLexicographicallySmaller(const std::string& str1, const std::string& str2) {
    size_t length1 = str1.length();
    size_t length2 = str2.length();
    size_t minLength = std::min(length1, length2);

    for (size_t i = 0; i < minLength; ++i) {
        if (str1[i] < str2[i]) {
            return true;
        } else if (str1[i] > str2[i]) {
            return false;
        }
    }

    return length1 < length2;
}

In C++, we use std::string and its length() function. Individual characters are accessed using array-like syntax. The std::min function is used to find the shorter length.

Python Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def is_lexicographically_smaller(str1, str2):
    length1 = len(str1)
    length2 = len(str2)
    min_length = min(length1, length2)

    for i in range(min_length):
        if ord(str1[i]) < ord(str2[i]):
            return True
        elif ord(str1[i]) > ord(str2[i]):
            return False

    return length1 < length2

In Python, we use len() to get the string lengths and ord() to get the ASCII value of a character. We use min to get the shorter length for loop iteration.

Understanding lexicographic comparison is crucial for string manipulation, sorting algorithms, and various other computer science applications.