Skip to main content

Command Palette

Search for a command to run...

Remove K Digits

Published
1 min read
Remove K Digits
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

LeetCode Problem - 402

import java.util.*;

class Solution {
    public String removeKdigits(String num, int k) {
        // Create a stack to store digits
        Stack<Character> stack = new Stack<>();

        // Iterate through each digit in the number
        for (char digit : num.toCharArray()) {
            // Remove digits from the stack if they are greater than the current digit and k > 0
            while (k > 0 && !stack.isEmpty() && stack.peek() > digit) {
                stack.pop();
                k--;
            }

            // Push the current digit onto the stack
            stack.push(digit);
        }

        // Remove remaining digits from the stack if k is still greater than 0
        while (k > 0) {
            stack.pop();
            k--;
        }

        // Build the result string using StringBuilder
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            result.insert(0, stack.pop());
        }

        // Remove leading zeros from the result
        while (result.length() > 0 && result.charAt(0) == '0') {
            result.deleteCharAt(0);
        }

        // If result is empty, return "0", otherwise return the result
        return result.length() == 0 ? "0" : result.toString();
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.