Open In App

Lexicographically largest string by merging identical adjacent letters into previous letter

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer N representing a string of length N with only the letter ‘z,’ the task is to find the Lexicographically largest string by merging adjacent identical letters into a single letters of previous alphabet (e.g. Merging “zz” would become “y” and Merging “yy” would become “x” and so on).

Note: “aa” cannot be further mergered.

Examples :

Input: N = 10
Output: db
Explanation: The original string “aaaaaaaaaa” can be transformed as follows.

  • “zzzzzzzzzz”
  • “yyyyy”
  • “xxy”
  • “wy”

Input : N = 2
Output: y

Approach:

Find the largest power of 2 in N, because the largest power of 2 represents the maximum number of consecutive ‘z‘s that can be transformed into the previous letter, then construct the resulting string and then convert the resulting value into the corresponding alphabet.

Start with the first letter ‘z‘ and Subtract the value of the largest power of 2 from N, repeat the process until N becomes 0 and then finally convert the resulting value into the corresponding alphabet.

Steps-by-step approach:

  • Finds the largest power of 2 in the given number n (capped at 25).
  • Returns a pair with the exponent and the value of the largest power of 2.
  • Constructs a string by repeatedly finding and appending characters based on the largest power of 2 in n.
  • Using the largestPowerof2() function to find and append the corresponding character and Continue the process until n becomes zero.
  • Return the constructed string.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
// Added typedef for long long
typedef long long ll;
 
pair<ll, ll> largestPowerof2(ll n)
{
    ll ans = 0;
    for (ll i = 30; i >= 0; i--) {
        if ((1LL << i) & n) {
            ans = i;
            break;
        }
    }
    // we do not want the character less than "a" ( which
    // is made up of 2^25 's "z" )
    ans = min(25LL, ans);
    return { ans, 1LL << ans };
}
 
string constructString(ll n)
{
    string str = "zyxwvutsrqponmlkjihgfedcba";
    string ans = "";
    while (n) {
        pair<ll, ll> a = largestPowerof2(n);
        ll pw = a.first;
        ll value = a.second;
        ans += str[pw];
        n -= value;
    }
    return ans;
}
 
int main()
{
    int n = 10;
    string result = constructString(n);
    cout << result;
    return 0;
}


Java




import java.util.*;
 
public class Main {
    // Added a static inner class for pair
    static class Pair {
        long first;
        long second;
 
        Pair(long first, long second) {
            this.first = first;
            this.second = second;
        }
    }
 
    static Pair largestPowerof2(long n) {
        long ans = 0;
        for (long i = 30; i >= 0; i--) {
            if (((1L << i) & n) != 0) {
                ans = i;
                break;
            }
        }
        // we do not want the character less than "a" ( which
        // is made up of 2^25 's "z" )
        ans = Math.min(25, ans);
        return new Pair(ans, 1L << ans);
    }
 
    static String constructString(long n) {
        String str = "abcdefghijklmnopqrstuvwxyz";
        StringBuilder ans = new StringBuilder();
        while (n != 0) {
            Pair a = largestPowerof2(n);
            long pw = a.first;
            long value = a.second;
            ans.append(str.charAt((int) pw));
            n -= value;
        }
        return ans.toString();
    }
 
    public static void main(String[] args) {
        long n = 11;
        String result = constructString(n);
        System.out.println(result);
    }
}


Python3




# Function to find the largest power of 2 in a given number 'n'
def largestPowerof2(n):
    ans = 0
    # Loop through bit positions from 30 to 0 (inclusive)
    # to find the highest bit that is set to 1
    for i in range(30, -1, -1):
        if (1 << i) & n:  # Check if the bit is set (equals 1)
            ans = # Store the position of the highest bit that is set
            break  # Exit the loop after finding the highest bit
    # Limit the position to 25 as 'a' (2^25) is the lowest character needed
    ans = min(25, ans)
    return ans, 1 << ans  # Return the position and the corresponding power of 2
 
# Function to construct a string based on the powers of 2 in the given number 'n'
def constructString(n):
    str = "zyxwvutsrqponmlkjihgfedcba"  # Characters in reverse alphabetical order
    ans = ""
    # Continue the loop until 'n' becomes zero
    while n:
        pw, value = largestPowerof2(n)  # Find the position and power of 2 for 'n'
        ans += str[pw]  # Add the corresponding character to the result string
        n -= value  # Subtract the value corresponding to the character added
    return ans  # Return the constructed string
 
# Main function to demonstrate the code
def main():
    n = 10  # Input number
    result = constructString(n)  # Call the function to construct the string
    print(result)  # Print the final constructed string
 
# Check if the script is being run as the main program
if __name__ == "__main__":
    main()  # Execute the main function


C#




using System;
 
public class Program
{
    public static Tuple<int, long> LargestPowerof2(long n)
    {
        int ans = 0;
        for (int i = 30; i >= 0; i--)
        {
            if (((1L << i) & n) != 0)
            {
                ans = i;
                break;
            }
        }
        // We do not want the character less than "a" ( which
        // is made up of 2^25 's "z" )
        ans = Math.Min(25, ans);
        return Tuple.Create(ans, 1L << ans);
    }
 
    public static string ConstructString(long n)
    {
        string str = "zyxwvutsrqponmlkjihgfedcba";
        string ans = "";
        while (n > 0)
        {
            Tuple<int, long> a = LargestPowerof2(n);
            int pw = a.Item1;
            long value = a.Item2;
            ans += str[pw];
            n -= value;
        }
        return ans;
    }
 
    public static void Main()
    {
        long n = 10;
        string result = ConstructString(n);
        Console.WriteLine(result);
    }
}
 
 
// this code is contributed by shivamgupta310570


Javascript




//Javascript Code
 
//Function to find the largest power of 2 in a given number 'n'
function largestPowerof2(n) {
    let ans = 0;
    for (let i = 30; i >= 0; i--) {
        if ((1 << i) & n) {
            ans = i;
            break;
        }
    }
    // we do not want the character less than "a" ( which
    // is made up of 2^25 's "z" )
    ans = Math.min(25, ans);
    return [ans, 1 << ans];
}
 
//Function to construct a string based on the powers of 2 in the given number 'n'
function constructString(n) {
    let str = "zyxwvutsrqponmlkjihgfedcba";
    let ans = "";
    //Continue the loop until 'n' becomes zero
    while (n) {
        let a = largestPowerof2(n);
        let pw = a[0];
        let value = a[1];
        ans += str[pw];
        n -= value;
    }
    return ans; //Return the constructed string
}
 
// Inputs
let n = 10;
 
let result = constructString(n);
console.log(result);


Output

wy

Time Complexity : O(log n), the loop runs a constant number of times (dependent on the binary representation of n)
Auxiliary Space : O(1), uses a constant amount of space for variables.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads