The Indian Engineer

Problem 650 2 Keys Keyboard

Posted on Last edited 5 mins

Math Dynamic-Programming

Problem Statement

Link - Problem 650

Question

There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:

Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.

Example 1

Input: n = 3
Output: 3
Explanation: Initially, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Example 2

Input: n = 1
Output: 0

Constraints

Solution

// Recusrive solution
class Solution {
private:
    int targetLength;

    int findMinSteps(int currentLength, int clipboardLength) {
        if (currentLength == targetLength) return 0;
        if (currentLength > targetLength) return INT_MAX / 2;

        int copyAndPaste = 2 + findMinSteps(currentLength * 2, currentLength);
        int pasteOnly = 1 + findMinSteps(currentLength + clipboardLength, clipboardLength);

        return min(copyAndPaste, pasteOnly);
    }

public:
    int minSteps(int n) {
        if (n == 1)
            return 0;
        targetLength = n;
        return 1 + findMinSteps(1, 1);
    }
};
// Using memoization
class Solution {
private:
    int targetLength;
    vector<vector<int>> cache;

    int calculateMinOps(int currentLength, int clipboardLength) {
        if (currentLength == targetLength) return 0;
        if (currentLength > targetLength) return INT_MAX / 2;

        if (cache[currentLength][clipboardLength] != -1) {
            return cache[currentLength][clipboardLength];
        }

        int pasteOption = 1 + calculateMinOps(currentLength + clipboardLength, clipboardLength);
        int copyPasteOption = 2 + calculateMinOps(currentLength * 2, currentLength);

        int result = min(pasteOption, copyPasteOption);
        cache[currentLength][clipboardLength] = result;

        return result;
    }

public:
    int minSteps(int n) {
        if (n == 1) return 0;
        targetLength = n;
        cache = vector<vector<int>>(n + 1, vector<int>(n / 2 + 1, -1));
        return 1 + calculateMinOps(1, 1);
    }
};

// Using factorization

class Solution {
public:
    int minSteps(int n) {
        if (n == 1)
            return 0;
        int sqrtN = sqrt(n);
        int total_operations = 0;
        for (int factor = 2; factor <= sqrtN; factor++) {
            while (n % factor == 0) {
                total_operations += factor;
                n /= factor;
            }
        }
        if (n > 1) {
            total_operations += n;
        }
        return total_operations;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Memoization O(n^2) O(n^2)
Factorization O(sqrt(n)) O(1)

Explanation

1. Intuition

2. Implementation