< Summary

Information
Class: LeetCode.Algorithms.RemoveKDigits.RemoveKDigitsStack
Assembly: LeetCode
File(s): D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\RemoveKDigits\RemoveKDigitsStack.cs
Line coverage
100%
Covered lines: 30
Uncovered lines: 0
Coverable lines: 30
Total lines: 67
Line coverage: 100%
Branch coverage
90%
Covered branches: 18
Total branches: 20
Branch coverage: 90%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
RemoveKdigits(...)90%2020100%

File(s)

D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\RemoveKDigits\RemoveKDigitsStack.cs

#LineLine coverage
 1// --------------------------------------------------------------------------------
 2// Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv).
 3// All Rights Reserved.
 4// --------------------------------------------------------------------------------
 5// This software is the confidential and proprietary information of Eugene Eremeev
 6// (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not
 7// disclose such Confidential Information and shall use it only in accordance with
 8// the terms of the license agreement you entered into with Eugene Eremeev (also
 9// known as Yevhenii Yeriemeieiv).
 10// --------------------------------------------------------------------------------
 11
 12namespace LeetCode.Algorithms.RemoveKDigits;
 13
 14/// <inheritdoc />
 15public class RemoveKDigitsStack : IRemoveKDigits
 16{
 17    /// <summary>
 18    ///     Time complexity - O(n)
 19    ///     Space complexity - O(n)
 20    /// </summary>
 21    /// <param name="num"></param>
 22    /// <param name="k"></param>
 23    /// <returns></returns>
 24    public string RemoveKdigits(string num, int k)
 825    {
 826        if (k == num.Length)
 227        {
 228            return "0";
 29        }
 30
 631        var stack = new Stack<char>();
 32
 16033        foreach (var digit in num)
 7134        {
 9235            while (k > 0 && stack.Count > 0 && stack.Peek() > digit)
 2136            {
 2137                stack.Pop();
 38
 2139                k--;
 2140            }
 41
 7142            stack.Push(digit);
 7143        }
 44
 745        while (k > 0 && stack.Count > 0)
 146        {
 147            stack.Pop();
 48
 149            k--;
 150        }
 51
 652        var resultArray = stack.ToArray();
 53
 654        Array.Reverse(resultArray);
 55
 656        var startIndex = 0;
 57
 1158        while (startIndex < resultArray.Length && resultArray[startIndex] == '0')
 559        {
 560            startIndex++;
 561        }
 62
 663        return startIndex == resultArray.Length
 664            ? "0"
 665            : new string(resultArray, startIndex, resultArray.Length - startIndex);
 866    }
 67}