Lowest Number by Removing k digits
Last Updated :
23 Jul, 2025
Given a string s
consisting of digits and an integer k
, remove k
digits from the string to form the smallest possible number, maintaining the order of the remaining digits. The resulting number should not have leading zeros. if the number is empty after removing digits, return "0"
.
Examples:
Input: s = "4325043", k = 3
Output: "2043"
Explanation: Remove digits to get the smallest possible number while maintaining order. The result after removing 3 digits is "2043".
Input: s = "765028321", k = 5
Output: "221"
Explanation: Remove 5 digits to form the smallest possible number. The result is "0221" and since we are not supposed to keep leading 0s, we get "221"
Input: s = "121198", k = 2
Output: "1118"
Explanation: Remove 2 digits to get the smallest number "1118".
[Approach 1] Using Greedy and Recursion - O(n x k) time and O(n) space
The idea is based on the following facts
- If n is the length of the given string, then there would be n-k digits in the result if there are no leading 0s.
- A digit among first (k+1) must be there in resultant number.
- And all digits preceding the minimum digit selected in the above step should not be part of the result because these are leading digits and will make the result higher as the order of the digits has to be maintained in result.
- So we greedily pick the smallest of the first (k+1) digits and put it in result, and recur for string after the index of the smallest
C++
#include <bits/stdc++.h>
using namespace std;
string lowestNum(string s, int k) {
// Base Case 1: If k == 0, return the whole 's'
if (k == 0) {
return s;
}
int n = s.size();
// Base Case 2: If 'n' is smaller
// or equal to k, everything can be removed
if (n <= k) {
return "";
}
// Find the smallest character among
// the first (k+1) characters of 's'
int minIdx = 0;
for (int i = 1; i <= k; ++i) {
if (s[i] < s[minIdx]) {
minIdx = i;
}
}
// Append 's[minIdx]' and recur for the substring after minIdx
return s[minIdx] + lowestNum(s.substr(minIdx + 1), k - minIdx);
}
string removeK(string s) {
int i = 0;
while (i < s.size() && s[i] == '0') {
i++;
}
return i == s.size() ? "0" : s.substr(i);
}
int main() {
string s = "765028321";
int k = 5;
string res = lowestNum(s, k);
cout << removeK(res) << "\n";
return 0;
}
Java
import java.util.*;
class GfG{
static String lowestNum(String s, int k) {
// Base Case 1: If k == 0, return the whole 's'
if (k == 0) {
return s;
}
int n = s.length();
// Base Case 2: If 'n' is smaller
// or equal to k, everything can be removed
if (n <= k) {
return "";
}
// Find the smallest character among
// the first (k+1) characters of 's'
int minIdx = 0;
for (int i = 1; i <= k; ++i) {
if (s.charAt(i) < s.charAt(minIdx)) {
minIdx = i;
}
}
// Append 's[minIdx]' and recur for the substring after minIdx
return s.charAt(minIdx) + lowestNum(s.substring(minIdx + 1), k - minIdx);
}
static String removeK(String s) {
int i = 0;
while (i < s.length() && s.charAt(i) == '0') {
i++;
}
return i == s.length() ? "0" : s.substring(i);
}
public static void main(String[] args) {
String s = "765028321";
int k = 5;
String res = lowestNum(s, k);
System.out.println(removeK(res));
}
}
Python
def lowest_num(s, k):
# Base Case 1: If k == 0, return the whole 's'
if k == 0:
return s
n = len(s)
# Base Case 2: If 'n' is smaller
# or equal to k, everything can be removed
if n <= k:
return ""
# Find the smallest character among
# the first (k+1) characters of 's'
min_idx = 0
for i in range(1, k + 1):
if s[i] < s[min_idx]:
min_idx = i
# Append 's[min_idx]' and recur for the substring after minIdx
return s[min_idx] + lowest_num(s[min_idx + 1:], k - min_idx)
def remove_k(s):
i = 0
while i < len(s) and s[i] == '0':
i += 1
return "0" if i == len(s) else s[i:]
s = "765028321"
k = 5
res = lowest_num(s, k)
print(remove_k(res))
C#
using System;
class GfG{
static string LowestNum(string s, int k) {
// Base Case 1: If k == 0, return the whole 's'
if (k == 0) {
return s;
}
int n = s.Length;
// Base Case 2: If 'n' is smaller
// or equal to k, everything can be removed
if (n <= k) {
return "";
}
// Find the smallest character among
// the first (k+1) characters of 's'
int minIdx = 0;
for (int i = 1; i <= k; ++i) {
if (s[i] < s[minIdx]) {
minIdx = i;
}
}
// Append 's[minIdx]' and recur for the substring after minIdx
return s[minIdx] + LowestNum(s.Substring(minIdx + 1), k - minIdx);
}
static string RemoveK(string s) {
int i = 0;
while (i < s.Length && s[i] == '0') {
i++;
}
return i == s.Length ? "0" : s.Substring(i);
}
static void Main() {
string s = "765028321";
int k = 5;
string res = LowestNum(s, k);
Console.WriteLine(RemoveK(res));
}
}
JavaScript
// Function to find the lowest number by removing k digits
function lowestNum(s, k) {
// Base Case 1: If k == 0, return the whole 's'
if (k === 0) {
return s;
}
const n = s.length;
// Base Case 2: If 'n' is smaller
// or equal to k, everything can be removed
if (n <= k) {
return "";
}
// Find the smallest character among
// the first (k+1) characters of 's'
let minIdx = 0;
for (let i = 1; i <= k; i++) {
if (s[i] < s[minIdx]) {
minIdx = i;
}
}
// Append 's[minIdx]' and recur for the substring after minIdx
return s[minIdx] + lowestNum(s.slice(minIdx + 1), k - minIdx);
}
function removeK(s) {
let i = 0;
while (i < s.length && s[i] === '0') {
i++;
}
return i === s.length ? "0" : s.slice(i);
}
const s = "765028321";
const k = 5;
const res = lowestNum(s, k);
console.log(removeK(res));
[Approach 2] Using Deque - O(n+k) time and O(n) space
We use greedy selection to pick the smallest digit, ensuring the smallest number. A deque efficiently stores and manages digits, removing larger ones from the back while maintaining order. Leading zeros are then removed to ensure a valid result.
C++
#include <bits/stdc++.h>
using namespace std;
void sortedInsert(deque<char>& dq, char ch)
{
// If deque is empty, simply push the character
if (dq.empty()) {
dq.push_back(ch);
} else {
char temp = dq.back();
// Remove digits from the back of deque
// that are larger than the current character
while (temp > ch && !dq.empty()) {
dq.pop_back();
if (!dq.empty())
temp = dq.back();
}
// Insert the current char at back in the deque
dq.push_back(ch);
}
}
// Function to build the smallest number by removing 'k' digits
string lowestNum(string s, int k)
{
int n = s.length();
int digitsToKeep = n - k;
// Deque to store digits in non-decreasing order
deque<char> dq;
string res = "";
// Iterate through the first (n - k) characters of 's'
int i;
for (i = 0; i <= n - digitsToKeep; i++) {
sortedInsert(dq, s[i]);
}
// Process the remaining characters
while (i < n) {
// Add the smallest digit to the result string
res += dq.front();
dq.pop_front();
// Insert the next character into
// the deque maintaining order
sortedInsert(dq, s[i]);
i++;
}
// Add the last remaining digit in the deque to the result
res += dq.front();
dq.pop_front();
return res;
}
// Function to remove leading zeros from the final result
string removeLe(string s, int k)
{
string res = lowestNum(s, k);
string ans = "";
int flag = 0;
// Traverse through the result string
// and remove leading zeros
for (int i = 0; i < res.length(); i++) {
if (res[i] != '0' || flag == 1) {
flag = 1;
ans += res[i];
}
}
// If the result string is empty, return "0",
// else return the result string
return ans.empty() ? "0" : ans;
}
int main()
{
string s = "765028321";
int k = 5;
cout << removeLe(s, k) << endl;
return 0;
}
Python
from collections import deque
def sorted_insert(dq, ch):
# If deque is empty, simply push the character
if not dq:
dq.append(ch)
else:
# Remove digits from the back of deque
# that are larger than the current character
while dq and dq[-1] > ch:
dq.pop()
# Insert the current char at back in the deque
dq.append(ch)
# Function to build the smallest number by removing 'k' digits
def lowest_num(s, k):
n = len(s)
digits_to_keep = n - k
# Deque to store digits in non-decreasing order
dq = deque()
res = ""
# Iterate through the first (n - k) characters of 's'
for i in range(n - digits_to_keep + 1):
sorted_insert(dq, s[i])
# Process the remaining characters
for i in range(n - digits_to_keep + 1, n):
# Add the smallest digit to the result string
res += dq.popleft()
# Insert the next character into
# the deque maintaining order
sorted_insert(dq, s[i])
# Add the last remaining digit in the deque to the result
res += dq.popleft()
return res
# Function to remove leading zeros from the final result
def remove_le(s, k):
res = lowest_num(s, k)
ans = ""
flag = 0
# Traverse through the result string
# and remove leading zeros
for char in res:
if char != '0' or flag == 1:
flag = 1
ans += char
# If the result string is empty, return "0",
# else return the result string
return ans if ans else "0"
if __name__ == '__main__':
s = "765028321"
k = 5
print(remove_le(s, k))
JavaScript
function sortedInsert(dq, ch) {
// If deque is empty, simply push the character
if (dq.length === 0) {
dq.push(ch);
} else {
// Remove digits from the back of deque
// that are larger than the current character
while (dq.length > 0 && dq[dq.length - 1] > ch) {
dq.pop();
}
// Insert the current char at back in the deque
dq.push(ch);
}
}
// Function to build the smallest number by removing 'k' digits
function lowestNum(s, k) {
let n = s.length;
let digitsToKeep = n - k;
// Deque to store digits in non-decreasing order
let dq = [];
let res = "";
// Iterate through the first (n - k) characters of 's'
for (let i = 0; i <= n - digitsToKeep; i++) {
sortedInsert(dq, s[i]);
}
// Process the remaining characters
for (let i = n - digitsToKeep + 1; i < n; i++) {
// Add the smallest digit to the result string
res += dq.shift();
// Insert the next character into
// the deque maintaining order
sortedInsert(dq, s[i]);
}
// Add the last remaining digit in the deque to the result
res += dq.shift();
return res;
}
// Function to remove leading zeros from the final result
function removeLe(s, k) {
let res = lowestNum(s, k);
let ans = "";
let flag = false;
// Traverse through the result string
// and remove leading zeros
for (let char of res) {
if (char !== '0' || flag) {
flag = true;
ans += char;
}
}
// If the result string is empty, return "0",
// else return the result string
return ans.length === 0 ? "0" : ans;
}
let s = "765028321";
let k = 5;
console.log(removeLe(s, k));
Time Complexity: O(n+k), n is length of string
Auxiliary Space: O(n)
[Approach 3] Using Stack - O(n+k) time and O(n) space
We use a stack to greedily remove larger digits to form the smallest possible number. As we process each digit, we remove larger ones from the stack, ensuring the smallest number. Leading zeros are discarded, and if digits remain to be removed, we pop more from the stack. The final number is formed from the remaining stack.
C++
#include <bits/stdc++.h>
using namespace std;
string remKdig(string s, int k)
{
int n = s.size();
stack<char> stk;
for (char c : s) {
while (!stk.empty() && k > 0 && stk.top() > c) {
stk.pop();
k -= 1;
}
if (!stk.empty() || c != '0')
stk.push(c);
}
while (!stk.empty() && k--)
stk.pop();
if (stk.empty())
return "0";
while (!stk.empty()) {
s[n - 1] = stk.top();
stk.pop();
n -= 1;
}
return s.substr(n);
}
int main()
{
string s = "765028321";
int k = 5;
cout << remKdig(s, k);
return 0;
}
Java
import java.util.Stack;
public class GfG{
public static String remKdig(String s, int k) {
int n = s.length();
Stack<Character> stk = new Stack<>();
for (char c : s.toCharArray()) {
while (!stk.isEmpty() && k > 0 && stk.peek() > c) {
stk.pop();
k--;
}
if (!stk.isEmpty() || c != '0')
stk.push(c);
}
while (!stk.isEmpty() && k-- > 0)
stk.pop();
if (stk.isEmpty())
return "0";
StringBuilder result = new StringBuilder();
while (!stk.isEmpty()) {
result.append(stk.pop());
}
return result.reverse().toString();
}
public static void main(String[] args) {
String s = "765028321";
int k = 5;
System.out.println(remKdig(s, k));
}
}
Python
def remKdig(s, k):
n = len(s)
stk = []
for c in s:
while stk and k > 0 and stk[-1] > c:
stk.pop()
k -= 1
if stk or c != '0':
stk.append(c)
while stk and k > 0:
stk.pop()
k -= 1
if not stk:
return "0"
return ''.join(stk)
s = "765028321"
k = 5
print(remKdig(s, k))
C#
using System;
using System.Collections.Generic;
class GfG{
public static string RemKDig(string s, int k) {
int n = s.Length;
Stack<char> stk = new Stack<char>();
foreach (char c in s) {
while (stk.Count > 0 && k > 0 && stk.Peek() > c) {
stk.Pop();
k--;
}
if (stk.Count > 0 || c != '0')
stk.Push(c);
}
while (stk.Count > 0 && k-- > 0)
stk.Pop();
if (stk.Count == 0)
return "0";
char[] result = new char[n - stk.Count];
int index = result.Length - 1;
while (stk.Count > 0) {
result[index--] = stk.Pop();
}
return new string(result);
}
static void Main() {
string s = "765028321";
int k = 5;
Console.WriteLine(RemKDig(s, k));
}
}
JavaScript
function remKdig(s, k) {
let n = s.length;
let stk = [];
for (let c of s) {
while (stk.length > 0 && k > 0 && stk[stk.length - 1] > c) {
stk.pop();
k--;
}
if (stk.length > 0 || c !== '0')
stk.push(c);
}
while (stk.length > 0 && k-- > 0)
stk.pop();
if (stk.length === 0)
return "0";
return stk.join('');
}
let s = "765028321";
let k = 5;
console.log(remKdig(s, k));
Remove K Digits | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem