Game with Strings (original) (raw)

Last Updated : 5 Dec, 2025

Geek like playing with strings, and one day he discovered a game. He gave one of his friends a string consisting of digits **0 to 9 and asked him to create the **largest lexicographically possible string out of it while keeping a few rules in mind.

Help Geek's friend in creating the **largest lexicographical possible string.

Example:

**Input: s = "3147"
**Output: "7320"
**Explanation:
Delete 1 and insert 0 at 3rd index. New String = "3470".
Delete 3 and insert 2 at 2nd index. New String = "4720".
Delete 4 and insert 3 at 1st index. New String = "7320".

**Input: s = "0"
**Output: "0"
**Explanation: Nothing need to be done in this string.

Approach: Greedy Transformation + Sorting

The key idea is to understand how each digit affects the final lexicographical order after applying the operation. Since we can replace a digit with its (digit − 1) and insert it anywhere, we want every digit in the final string to become as large as possible.

Implementation:

We scan the string from right to left while keeping track of the maximum digit seen so far.

This is valid because smaller digits that appear before a larger digit will eventually be pushed down.
After this adjustment, we sort the string in descending order, because once all digits are reduced correctly, placing larger digits first always gives the lexicographically largest result.

This produces the largest possible string that can be formed using the allowed operations.

C++ `

// Language: C++

#include <bits/stdc++.h> using namespace std;

// Create largest lexicographical string string findLargestString(string s) { char mx = '0';

// Scan from right adjusting values
for (int i = s.size() - 1; i >= 0; i--) {
    if (s[i] >= mx)
        mx = s[i];
    else
        s[i] = max((char)'0', (char)(s[i] - 1));
}

// Sort descending to maximize lexicographic value
sort(s.begin(), s.end());
reverse(s.begin(), s.end());

return s;

}

int main() { string s = "3147"; cout << findLargestString(s) << endl; }

Java

// Language: Java

import java.util.*;

class GfG {

// Create largest lexicographical string
static String findLargestString(String s) {
    char[] arr = s.toCharArray();
    char mx = '0';

    // Scan from right adjusting values
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] >= mx)
            mx = arr[i];
        else
            arr[i] = (char)Math.max('0', arr[i] - 1);
    }

    // Sort descending to maximize lexicographic value
    Arrays.sort(arr);
    StringBuilder sb = new StringBuilder(new String(arr));
    sb.reverse();

    return sb.toString();
}

public static void main(String[] args) {
    String s = "3147";
    System.out.println(findLargestString(s));
}

}

Python

Language: Python

def findLargestString(s): arr = list(s) mx = '0'

# Scan from right adjusting values
for i in range(len(arr)-1, -1, -1):
    if arr[i] >= mx:
        mx = arr[i]
    else:
        arr[i] = str(max(0, int(arr[i]) - 1))

# Sort descending to maximize lexicographic value
arr.sort(reverse=True)
return "".join(arr)

Example

s = "3147" print(findLargestString(s))

C#

// Language: C#

using System; using System.Linq;

class GfG {

// Create largest lexicographical string
static string findLargestString(string s) {
    char[] arr = s.ToCharArray();
    char mx = '0';

    // Scan from right adjusting values
    for (int i = arr.Length - 1; i >= 0; i--) {
        if (arr[i] >= mx)
            mx = arr[i];
        else
            arr[i] = (char)Math.Max('0', arr[i] - 1);
    }

    // Sort descending to maximize lexicographic value
    arr = arr.OrderByDescending(c => c).ToArray();

    return new string(arr);
}

static void Main() {
    string s = "3147";
    Console.WriteLine(findLargestString(s));
}

}

JavaScript

// Language: JavaScript

function findLargestString(s) { let arr = s.split(''); let mx = '0';

// Scan from right adjusting values
for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] >= mx)
        mx = arr[i];
    else
        arr[i] = String(Math.max(0, Number(arr[i]) - 1));
}

// Sort descending to maximize lexicographic value
arr.sort((a, b) => b.localeCompare(a));

return arr.join('');

}

// Example let s = "3147"; console.log(findLargestString(s));

`

**Time complexity: O(n * log n)
**Auxiliary Space: O(1)