algoadvance

Leetcode 650. 2 Keys Keyboard

Problem Statement

You have a text editor with two special keys:

Initially, you have n ‘A’s written on the clipboard, and you can only perform two operations:

Given n, the goal is to find the minimum number of operations needed to get exactly n ‘A’s in the text.

Clarifying Questions

  1. Clarifications about the operation of the keys:
    • The ‘A’ key appends a single ‘A’.
    • The ‘Ctrl-V’ key pastes clipboard content and can only be used after a ‘Ctrl-C’ operation which copies the entire current text to the clipboard.
  2. Initial setup:
    • We start with exactly one ‘A’ in the text.
  3. Clipboard:
    • Any ‘Ctrl-C’ operation copies the entire current text to the clipboard.

Strategy

The problem boils down to dividing the task into finding the smallest number of steps required to reach n ‘A’s starting with one ‘A’. This can be approached as follows:

Dynamic Programming Approach

Define dp[i] as the minimum number of operations required to get i ‘A’s. Initially, we have:

For every value of i from 2 to n:

  1. Check each possible value j where j is a factor of i (i % j == 0).
  2. If j is a factor of i, then paste the content (i/j times) requiring i/j operations after copying j length text which also requires j operations. Therefore, it takes dp[j] + (i / j) operations in total to achieve i copies.

Code

public class TwoKeysKeyboard {
    public int minSteps(int n) {
        // Edge case: since 1 'A' requires 0 operations.
        if (n == 1) return 0;
        
        // Define the dp array where dp[i] will store the min operations to get i 'A's.
        int[] dp = new int[n + 1];
        
        // Start with 0 operations needed for 1 'A' (base case)
        dp[1] = 0;
        
        // Fill dp array from 2 to n
        for (int i = 2; i <= n; i++) {
            dp[i] = i; // Start with the maximum which is all 'A' operations

            for (int j = i - 1; j > 0; j--) {
                if (i % j == 0) { // If divisible, we can copy paste from j
                    dp[i] = dp[j] + (i / j);
                    break;
                }
            }
        }
        
        return dp[n];
    }

    public static void main(String[] args) {
        TwoKeysKeyboard solution = new TwoKeysKeyboard();
        int n = 9; // Example
        System.out.println("Minimum steps to get " + n + " 'A's: " + solution.minSteps(n));
    }
}

Time Complexity

This approach is efficient and feasible for typical input sizes within constraint limits.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI