(Hacker Rank) Smriti and the Strings - Solution

Link to the problem: https://www.hackerrank.com/contests/womens-codesprint/challenges/smriti-and-strings

For the solution, a stack was used to keep the lexicographically largest characters.


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       
        int numTests = sc.nextInt();
        for (int i = 0; i < numTests; i++) {
            String s = sc.next();
            int numEliminate = sc.nextInt();
           
            int count = 0;
            Deque<Character> stack = new ArrayDeque<Character>();
            for (int j = 0; j < s.length(); j++) {
                while (stack.size() > 0 && stack.peekLast() < s.charAt(j) && count < numEliminate) {
                    stack.pollLast();
                    count++;
                }
                stack.addLast(s.charAt(j));
            }
            StringBuilder sb = new StringBuilder();
            while (stack.size() > 0 && sb.length() < s.length() - numEliminate) {
                sb.append(stack.pollFirst());
            }
           
            System.out.println(sb.toString());
        }
    }
}



Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução