algoadvance

Leetcode 3210. Find the Encrypted String

Problem Statement

Given a string s, perform the following operation until the string becomes empty: remove the character at the position with the highest alphabetical value. If there are multiple such characters, remove the leftmost one. After each removal, append the removed character to a result string. The task is to return the resulting string after applying the above operations.

Example

Clarifying Questions

  1. Can the input string contain non-alphabetical characters?
    • No, it will only contain lowercase alphabetical characters.
  2. Is the string guaranteed to have at least one character?
    • Yes, it will always be a non-empty string.
  3. Can there be any constraints on the length of the input string?
    • Assume the length of the string is within reasonable limits for typical interview problems (e.g., 1 ≤ s.length ≤ 1000).

Strategy

  1. Initialize an empty result string.
  2. While the original string s is not empty:
    • Find the character with the highest alphabetical value.
    • If multiple characters have the highest value, select the leftmost one.
    • Remove this character from s.
    • Append this character to the result string.
  3. Return the result string.

Steps in Detail:

Time Complexity

Code Implementation

#include <iostream>
#include <string>

std::string findEncryptedString(const std::string &input) {
    std::string s = input;  // making a copy of input as we will modify it
    std::string result;

    while (!s.empty()) {
        int maxPos = 0;
        for (int i = 1; i < s.size(); ++i) {
            if (s[i] > s[maxPos]) {
                maxPos = i;
            }
        }
        result.push_back(s[maxPos]);
        s.erase(s.begin() + maxPos);
    }

    return result;
}

int main() {
    std::string input = "abacad";
    std::string output = findEncryptedString(input);
    std::cout << "Encrypted String: " << output << std::endl;  // Output should be "dbcaab"
    return 0;
}

Explanation of the Code

  1. Initialization:
    • Copy the input string s to a mutable string.
    • Initialize an empty result string result.
  2. Main Loop:
    • Iterate while s is not empty.
    • Inside the loop, find the maximum character in the string s by comparing each character (tracked using maxPos).
    • Append the maximum character to result.
    • Remove the character from the original string s using erase.
  3. Output:
    • Return the result string.

This solution respects the requirements and ensures each character is processed according to the given rules. The provided example demonstrates the expected output correctly.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI