24. Lexicographically Largest String After K Deletions
โ GFG solution to the Lexicographically Largest String After K Deletions problem: remove exactly k characters to get the largest possible string using greedy approach. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given a string s consisting of lowercase English letters and an integer k, your task is to remove exactly k characters from the string. The resulting string must be the largest possible in lexicographical order, while maintaining the relative order of the remaining characters.
๐ Examples
Example 1
Input: s = "ritz", k = 2
Output: "tz"
Explanation: By removing two characters in all possible ways, we get:
"ri", "rt", "rz", "it", "iz", and "tz". Among these, "tz" is lexicographically largest.Example 2
Input: s = "zebra", k = 3
Output: "zr"
Explanation: Removing "e", "b", and "a" results in "zr", which is lexicographically largest.๐ Constraints
$1 \le \text{s.size()} \le 10^5$
$0 \le k < \text{s.size()}$
String consists of lowercase English letters only
โ
My Approach
The optimal approach uses a Greedy Algorithm with Monotonic Stack concept to achieve the lexicographically largest result:
Greedy String Manipulation
Core Strategy:
Remove smaller characters when a larger character appears, as long as we have deletions remaining.
This ensures we keep the largest possible characters in their relative positions.
Algorithm Steps:
Iterate through each character in the string.
While the result string is not empty, we have deletions left, and the last character in result is smaller than current character:
Remove the last character from result (this counts as one deletion).
Add the current character to the result.
After processing all characters, resize the result to final length (n - k).
Key Insight:
By removing smaller characters when larger ones appear, we maximize the lexicographical value of the remaining string.
The greedy choice at each step leads to the globally optimal solution.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. Each character is processed at most twice (once when added, once when potentially removed), resulting in linear time complexity.
Expected Auxiliary Space Complexity: O(n), as we use a result string that can grow up to the size of the input string during processing.
๐งโ๐ป Code (C++)
โก View Alternative Approaches with Code and Analysis
๐ 2๏ธโฃ Greedy Selection Approach
๐ก Algorithm Steps:
Let
len = n - k(final result length).For each position
iin the result (0 โค i < len), scans[startโฆk+i]to pick the maximal character.Append the maximal character to result, set
startto its index + 1, and continue.This ensures we always pick the largest possible character for each position while maintaining enough characters for remaining positions.
๐ Complexity Analysis:
Time: โฑ๏ธ O(nยท(nโk)) worst-case (O(nยฒ))
Auxiliary Space: ๐พ O(1) - Only uses constant extra space
โ
Why This Approach?
Simple "pick-max-in-window" logic that's easy to understand.
No auxiliary data structures needed.
Direct greedy selection without stack operations.
๐ 3๏ธโฃ Stack-Based Monotonic Approach
๐ก Algorithm Steps:
Use a stack to maintain decreasing order of characters.
Pop smaller characters when a larger character is found and removals are available.
Handle remaining removals at the end by popping from stack.
Reconstruct result from stack (requires reversal).
๐ Complexity Analysis:
Time: โฑ๏ธ O(n)
Auxiliary Space: ๐พ O(n) - For stack storage
โ
Why This Approach?
Clear stack-based implementation for monotonic sequence.
Easier to visualize the greedy removal process.
Classic data structure approach for such problems.
๐ 4๏ธโฃ Deque-Based Sliding Window
๐ก Algorithm Steps:
Use deque to maintain potential candidates with flexible operations.
Remove smaller elements from back when larger element arrives.
Maintain size constraint throughout the process.
Extract final result from front of deque.
๐ Complexity Analysis:
Time: โฑ๏ธ O(n)
Auxiliary Space: ๐พ O(n) - For deque storage
โ
Why This Approach?
Flexible front and back operations.
Natural sliding window behavior.
Good for scenarios requiring both-end access.
๐ 5๏ธโฃ Vector-Based Greedy with Index Tracking
๐ก Algorithm Steps:
Store characters with their original indices for complex tracking.
Apply greedy removal strategy while maintaining index information.
Reconstruct result maintaining original order.
Useful when index information is crucial for the solution.
๐ Complexity Analysis:
Time: โฑ๏ธ O(n)
Auxiliary Space: ๐พ O(n) - For vector storage
โ
Why This Approach?
Explicit index tracking for complex scenarios.
Vector operations are cache-friendly.
Suitable when additional metadata is needed.
๐ ๐ Comprehensive Comparison of All Approaches
๐ Approach
โฑ๏ธ Time Complexity
๐พ Space Complexity
๐ฏ Best Use Case
โ Pros
โ ๏ธ Cons
๐ String Manipulation
๐ข O(n)
๐ข O(n)
Competitive programming, optimal speed
โก Direct operations, minimal overhead
๐งฎ String resize operations
๐ฏ Greedy Selection
๐ด O(nยฒ)
๐ข O(1)
Small inputs, educational purposes
๐พ No extra space, simple logic
โฐ Quadratic time complexity
๐ Stack-Based
๐ข O(n)
๐ก O(n)
Learning data structures, clear visualization
๐ง Clear monotonic logic
๐พ Extra space, requires reversal
๐บ Deque-Based
๐ข O(n)
๐ก O(n)
Complex scenarios, flexible operations
๐ Both-end access flexibility
๐พ Deque operation overhead
๐ Vector with Index
๐ข O(n)
๐ก O(n)
When index tracking is crucial
โก Cache-friendly, metadata support
๐งฎ Complex pair management
๐ Best Choice Recommendations
๐ฏ Scenario
๐๏ธ Recommended Approach
๐ฅ Performance Rating
๐ Notes
โก Maximum performance, competitive programming
๐ฅ String Manipulation
โ โ โ โ โ
Best overall choice
๐ Learning algorithms, understanding the logic
๐ฅ Stack-Based
โ โ โ โ โ
Most educational
๐พ Memory-constrained environments
๐ฅ Greedy Selection
โ โ โ โโ
O(1) space but O(nยฒ) time
๐ง Complex requirements, debugging needed
๐๏ธ Vector with Index
โ โ โ โ โ
Easy to modify and debug
๐ Flexible operations, both-end access needed
๐ Deque-Based
โ โ โ โ โ
Good for complex scenarios
๐งโ๐ป Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Let's make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated