Min Steps to One Using Dynamic Programming

Given a positive integer N, your task is to determine the minimum number of steps required to reduce N to 1.

Allowed Operations:

1) Subtract 1 from it: n = n - 1
2) If n is divisible by 2, divide it by 2: if n % 2 == 0, then n = n / 2
3) If n is divisible by 3, divide it by 3: if n % 3 == 0, then n = n / 3

Input:

The input starts with an integer 'T', the number of test cases.
Each of the next 'T' lines contains a single integer 'N'.

Output:

Return an integer for each test case which denotes the minimum steps needed to reduce the number to 1.

Example:

Input:
T = 1
N = 4
Output:
2
Explanation:

Starting from N = 4, divide by 2 to get 2, then subtract 1 to reach 1.

Constraints:

  • 1 <= T <= 5
  • 1 <= N <= 105

Time Limit: 1 second

Note:
This problem requires the implementation of the function that calculates the minimum steps, without printing the output.
AnswerBot
4mo

Find the minimum number of steps to reduce a positive integer to 1 using given operations.

  • Use dynamic programming to store the minimum steps for each number from 1 to N.

  • Iterate through each number fro...read more

Help your peers!
Select
Add answer anonymously...

Google Software Developer interview questions & answers

A Software Developer was asked 1mo agoQ. What are your goals?
A Software Developer was asked 2mo agoQ. What is the explanation of the Least Recently Used (LRU) cache algorithm?
A Software Developer was asked 3mo agoQ. What programming languages are you familiar with?

Popular interview questions of Software Developer

A Software Developer was asked 1mo agoQ1. What are your goals?
A Software Developer was asked 2mo agoQ2. What is the explanation of the Least Recently Used (LRU) cache algorithm?
A Software Developer was asked 3mo agoQ3. What programming languages are you familiar with?

Top HR questions asked in Google Software Developer

A Software Developer was asked 2mo agoQ1. Why should we choose you?
A Software Developer was asked 3mo agoQ2. How does the role fit your career plans?
A Software Developer was asked 8mo agoQ3. Explain your project in detail.
Google Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits