VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-largest-cube-formed-deleting-minimum-digits-number/

⇱ Largest Pefect Cube by Deleting Minimum Digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest Pefect Cube by Deleting Minimum Digits

Last Updated : 11 Jul, 2025

Given a number n, the task is to find the largest perfect cube that can be formed by deleting the fewest number of digits (possibly 0 digits). A number x is a perfect cube if it can be written as x = y3 for some integer y.
You can delete any digits from the given number n, but you cannot rearrange the digits. The goal is to find the largest perfect cube that can be formed with the remaining digits.

Examples:

Input: 4125
Output: 125
Explanation: Deleting '4' from 4125 forms 125, the largest perfect cube.

Input: 876
Output: 8
Explanation: Deleting '7' and '6' from 876 forms 8, the largest perfect cube.

[Naive Approach] Checking all subsequences - O(2^log nlog n) time and O(log n) space

The idea is to generate all possible subsequences of the given number, check if they are perfect cubes, and then keep track of the largest one. This will be inefficient for large numbers due to the number of subsequences.


Output
125

Time Complexity: O(2log n log n), due to the number of digits in n are log(n) + 1
Auxiliary Space: O(log n), maximum size of subsequence will be log n

[Expected Approach] Checking cubes till n - O(n^1/3 log n) and O(log n) space

The expected approach is to iterate through potential perfect cubes up to a n, and for each perfect cube, check if it can be formed as a subsequence of the given number n. This avoids generating all subsequences explicitly.


Output
125

Time Complexity: O(n1/3 log(n)), due to the number of digits in n are log(n) + 1
Auxiliary Space: O(log n), maximum size of subsequence will be log n

Comment
Article Tags:
Article Tags: