Prepin
Log in

Develop a string sorting algorithm that treats digits as numerical values.

Approach / Explanation

The prompt requires you to create a sorting algorithm for strings that treats digits as whole numbers rather than separate entities. Essentially, this represents a variation of lexicographical sorting, in which '2' precedes '10' due to its numerical value. Your goal is to develop a program that sorts '10' before '2', since it is considered smaller when evaluated as an integer. Here are some guidelines to keep in mind: Treat strings with digits as numerical values: For instance, the string '123' should be treated as the number 123. Be aware that not every string will contain numerical characters. Make sure your solution can handle a combination of numerical and alphabetical strings.

Suggested Answer

This is an illustration of how to achieve this in Python by utilizing the sorted function along with a custom key function. The custom key function determines whether a string can be converted to an integer; if it can, it performs the conversion; if not, it retains the string in its original form. This approach allows the sorted function to sort the values numerically rather than lexicographically. def sort_strings ( strings ) : def convert ( s ) : try : return int ( s ) except ValueError : return s return sorted ( strings , key = convert )

Alternative Answer

Here’s an alternative method in Java that utilizes a custom Comparator: import java . util . * ; public class Main { public static void main ( String [ ] args ) { String [ ] strings = { "10" , "1" , "20" , "b" , "a" } ; Arrays . sort ( strings , new Comparator < String > ( ) { public int compare ( String a , String b ) { try { return Integer . compare ( Integer . parseInt ( a ) , Integer . parseInt ( b ) ) ; } catch ( NumberFormatException e ) { return a . compareTo ( b ) ; } } } ) ; for ( String s : strings ) { System . out . println ( s ) ; } } } This Java program creates a Comparator that attempts to parse the strings as integers for comparison. If the parsing is successful, it compares them as integers; otherwise, it defaults to lexicographical comparison.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Bolt

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.