Minimum number of key presses to type the given string in C++Introduction:You can use dynamic programming to find the minimum number of key presses to type a given string in C++. The idea is to build a table where each entry dp[i][j] represents the minimum number of key presses required to type the substring s[i..j]. The table is filled in a bottom-up manner. Program:Output: Enter the string: abcdefghij Minimum number of keypresses: 10 Explanation:
In this example, the code starts by including necessary libraries, such as stream and vector. The minKeypresses function is defined to calculate the minimum keypresses required to type a given string. A 2D vector named dp is created to store the results. dp[i][j] will represent the minimum keypresses for the substring from index i to index j. The function takes a string as input:
The diagonal elements of the dp table are initialized to 1. This is because a substring of length 1 requires only one keypress. The function then iterates over all possible substring lengths (2 or more) and considers all possible substrings within the given string.
For each substring, it checks if the endpoints are the same (i.e., the substring is a palindrome). If so, it sets the keypresses to 1. If the endpoints are the same, the result is the same as for the substring without those endpoints.
The code then tries different partition points within the substring and updates the minimum keypresses accordingly. It checks all possible partitions and keeps track of the minimum keypresses required.
The final result is stored in dp[0][n - 1], where n is the length of the input string. It represents the minimum keypresses for the entire string.
The main function takes user input for the string. It calls the minKeypresses function with the entered string and prints the result. Complexity analysis: Time Complexity: The code uses a bottom-up dynamic programming approach to fill in the dp table. The two nested loops iterate over all possible substring lengths and positions within the string. The third loop iterates over possible partition points. Therefore, the time complexity is O(n^3), where 'n' is the length of the input string. Space Complexity: The 2D vector dp determines the space complexity. The size of the dp table is n x n, where 'n' is the length of the input string. Therefore, the space complexity is O(n^2) since it depends on the square of the input size. Approach 1: Using Greedy AlgorithmIterate through the string and count consecutive characters. If a character is repeated consecutively, you can consider typing the character and the number of times it repeats in a single keypress. Program:Output: Enter the string: JavaTpoint Minimum number of keypresses: 10 Explanation:
Takes a string s as input.
Checks if the string is empty. If it is, the function returns 0 as there are no characters to type.
Initializes totalKeypresses to 1. This is for the first character in the string.
Uses a loop to go through each character in the string. For each character, it counts how many consecutive characters are the same using a while loop. While counting, it moves to the next character until a different one is encountered.
Adds to totalKeypresses the count of consecutive characters plus an additional 1 for typing the character itself. If the count is 1 (i.e., a character without consecutive repetitions), it does not add an extra keypress for the count.
It returns the final value of totalKeypresses, representing the minimum keypresses needed to type the given string. Main Function:
It takes user input for the string.
Calls the minKeypressesGreedy function with the entered string.
Prints the minimum number of keypresses obtained from the function. Complexity analysis: Time Complexity: Iteration through String: The for loop iterates through each character in the string once. The while loop inside it counts consecutive characters. In the worst case, each character might be visited twice (once in the outer loop and once in the while loop). Therefore, the time complexity for the iteration is O(n), where 'n' is the length of the input string. Calculating Keypresses: The calculations inside the loop take constant time per character. The overall time complexity remains O(n). Main Function: The main function takes input and calls the minKeypressesGreedy function, which has a time complexity of O(n). The overall time complexity of the code is O(n). Space Complexity: Additional Variables: The code uses a constant amount of additional space regardless of the input size. Variables like totalKeypresses, count, and the loop variables don't depend on the input size. The space complexity is O(1), indicating constant space usage. Approach 2: Using Manacher's Algorithm for Longest Palindromic SubstringFind the longest palindromic substring in the given string. The length of the remaining string minus the length of the palindromic substring gives the minimum keypresses needed. Program:Output: Enter the string: abcde Minimum number of keypresses: 4 Explanation: Preprocessing Function (preprocess):
It takes a string s as input.
Inserts a '#' between each character in the string. It is done to handle both even and odd-length palindromes efficiently. Manacher's Algorithm Function (longestPalindromicSubstring):
Takes the preprocessed string as input.
Initializes variables for the center and right boundary of the rightmost palindrome found so far.
Creates an array to store the lengths of palindromes centered at each index.
Iterates through each character in the preprocessed string. Utilizes symmetry properties to avoid unnecessary comparisons and efficiently finds the length of palindromes centered at each index.
Updates the center and right boundary based on the palindromes found.
Finds the maximum length in the palindrome lengths array.
Returns the length of the longest palindromic substring. Minimum Keypresses Calculation Function (minKeypressesManacher):
Takes the original string as input.
Calls the longestPalindromicSubstring function to find the length of the longest palindromic substring.
Calculate the minimum keypresses by subtracting the length of the longest palindromic substring from the total length of the original string.
Returns the minimum keypresses. Main Function:
Takes user input for the original string.
Calls the minKeypressesManacher function with the entered string.
It prints the minimum number of keypresses obtained from the function. Complexity analysis: Time Complexity: Preprocessing Function (preprocess): Iterates through each character in the original string once to insert '#' between characters. The time complexity of this function is O(n), where 'n' is the length of the original string. Manacher's Algorithm Function (longestPalindromicSubstring): It iterates through each character in the preprocessed string once. The time complexity of Manacher's algorithm is O(n), where 'n' is the length of the preprocessed string. Minimum Keypresses Calculation Function (minKeypressesManacher): It calls the longestPalindromicSubstring function, which has a time complexity of O(n). Performs simple arithmetic operations, which take constant time. The overall time complexity of the code is O(n). Space Complexity: Preprocessing Function (preprocess): Creates a new string with length 2n (each character in the original string plus the inserted '#'). The space complexity of this function is O(n). Manacher's Algorithm Function (longestPalindromicSubstring): Uses additional space for the palindrome lengths array, which has length n. The space complexity of Manacher's algorithm is O(n). Minimum Keypresses Calculation Function (minKeypressesManacher): It uses constant space for variables. The space complexity is O(1). The overall space complexity of the code is O(n). Approach 3: Using Count Unique CharactersCount the number of unique characters in the string. The minimum keypresses would be the length of the string minus the count of unique characters. Program:Output: Enter the string: jtp Minimum number of keypresses: 0 Explanation:
The minKeypressesCountUnique function takes a strings as input.
Initializes an unordered set (uniqueCharacters) to keep track of unique characters encountered.
It iterates through each character in the string and inserts it into the set. The set automatically ensures uniqueness.
It calculates the minimum keypresses using the formula: length of string - number of unique characters.
Returns the minimum keypresses as the result. Complexity analysis: Time Complexity: Traverse and Insert (minKeypressesCountUnique function): Iterates through each character in the string once and inserts it into the unordered set. The time complexity of this operation is O(n), where 'n' is the length of the input string. Calculate Minimum Keypresses: Calculating the minimum keypresses involves finding the size of the unordered set. The time complexity of finding the size of an unordered set is O(1) on average. The overall time complexity of the code is O(n). Space Complexity: Space for Unique Characters (unordered set): The space complexity is influenced by the unordered set, which stores unique characters. In the worst case, the space required is O(min(n, m)), where 'n' is the length of the input string and 'm' is the number of unique characters. Additional Space: Other than the unordered set, the code uses a constant amount of additional space for variables like n, result, and the loop variables. The overall space complexity is O(min(n, m)), where 'n' is the length of the input string and 'm' is the number of unique characters. Approach 4: Using Divide and ConquerThe "Divide and Conquer" approach involves breaking down the problem into smaller segments, recursively solving each segment, and then combining the results to obtain the solution for the entire problem. In the context of finding the minimum keypresses for a given string, we can apply this approach by dividing the string into smaller parts, calculating keypresses for each part, and then combining the results. Program:Output: Enter the string: world Minimum number of keypresses: 5 Explanation: Function minKeypressesSegment: Represents a function that calculates the minimum keypresses for a given segment. This function can be customized based on characteristics of the segments. Function minKeypressesDivideConquer: It takes the input string s and the indices start and end to define the segment. Base case: If the segment has only one character, return 1 as typing a single character requires one keypress. Divide the segment into two halves (start to mid and mid+1 to end). Recursively calculate the minimum keypresses for each half. Combine the results based on the characteristics of the segments. In this example, we add the keypresses for each half. Return the combined result. Main Function: Takes user input for the original string. Calls the minKeypressesDivideConquer function with the entire string. Complexity analysis: Time Complexity: Recursive Calls (minKeypressesDivideConquer function): In each recursive call, the function divides the segment into two halves. The number of recursive calls is proportional to the depth of the recursion tree, which is logarithmic in the length of the input string. Each level of the recursion tree takes O(1) time to combine results and handle base cases. The overall time complexity is O(log n), where 'n' is the length of the input string. minKeypressesSegment Function (Custom Logic): The time complexity of this function depends on the custom logic implemented to calculate keypresses for a segment. In the provided example, it simply returns the length of the segment, which takes O(1) time. If more complex logic is implemented, the time complexity may vary. The recursive calls dominate the overall time complexity and are O(log n). Space Complexity: Stack Space (minKeypressesDivideConquer function): The space complexity is determined by the maximum depth of the recursion stack. In the worst case, the maximum depth is logarithmic in the length of the input string. Therefore, the space complexity due to recursion is O(log n). Additional Variables: The code uses a constant amount of additional space for variables like mid, leftKeypresses, rightKeypresses, and loop variables. The overall space complexity is O(1), indicating constant space usage. |