Remove Duplicate Characters
Remove Duplicate Characters
You have been given a string having space-separated multiple words. Reprint the string after
removing the characters that occur more than once in the string. You are supposed to remove the
later occurrences of a character.
testcase:
Input 2 :
quick fox jumps lake
Output 2 :
quick foxjmpslaein python
To achieve the desired result, you can write a Python function to process the string. Below is the
implementation:
python
def remove_duplicate_characters(s):
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result)
# Test case
input_2 = "quick fox jumps lake"
output_2 = remove_duplicate_characters(input_2)
print(output_2)
Explanation:
For the input `"quick fox jumps lake"`, the output will be:
quick foxjmpslae
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/42
Problem Statement
Given an array A of size N that contains only non-negative integers, find a continuous sub-array that
adds to a given number S and return the left and right indexes of that sub-array. In the case of
multiple subarrays, return the subarray indexes that come first when moving from left to right.
Note: Both the indexes in the array should be according to 1-based indexing. You have to return an
array list consisting of two elements, left and right. If no such subarray exists, return an array
consisting of element -1.
Example 1
Input:
N = 5, S = 12
A[5] = {1,2,3,7,5}
Output:
24
Explanation:
The sum of elements from the 2nd position to the 4th position is 12.
Example 2
Input:
N = 10, S = 15
A[10] = {1,2,3,4,5,6,7,8,9,10}
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/42
15
Explanation:
The sum of elements from the 1st position to the 5th position is 15.
Here is the Python code to solve the problem. It uses a sliding window (or two-pointer) approach to
efficiently find the continuous sub-array that adds up to the given sum S .
python
# Shrink the window from the left if the sum exceeds the target
while current_sum > s and left <= right:
current_sum -= arr[left]
left += 1
# Test cases
print(find_subarray_with_sum(5, 12, [1, 2, 3, 7, 5])) # Output: [2, 4]
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/42
print(find_subarray_with_sum(10, 15, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) # Output: [1, 5]
print(find_subarray_with_sum(3, 22, [1, 4, 5])) # Output: [-1]
Explanation:
Complexity:
Time Complexity: O(N ), as each element is processed at most twice (once by `right` and at most
once by `left`).
Space Complexity: O(1), as no additional space is used apart from variables.
Problem Statement:
Suppose you have been keeping an eye on the stock market for a while, and you have been tracking
the daily prices of a particular stock. You want to make a profit by buying and selling the stock at the
right time.
Given the array of prices of the stock on each day, you need to figure out the best strategy to
maximize your profit.
However, if the stock prices are constantly decreasing, there is no way for you to make a profit.
Example 1:
Input:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/42
7
Output:
865
Explanation:
Buy the stock on day 0 and sell it on day 3 => 310 – 100 = 210
Buy the stock on day 4 and sell it on day 6 => 695 – 40 = 655
Example 2:
Input:
arr[] = {4, 2, 2, 2, 4}
Output:
Explanation:
Maximum Profit = 2
Here is the Python solution to maximize the profit by identifying the optimal buy-and-sell days for the
given stock prices:
python
def max_profit(prices):
n = len(prices)
if n < 2:
return 0
max_profit = 0
return max_profit
# Test cases
print(max_profit([100, 180, 260, 310, 40, 535, 695])) # Output: 865
print(max_profit([4, 2, 2, 2, 4])) # Output: 2
print(max_profit([10, 8, 6, 4, 2])) # Output: 0
print(max_profit([1, 3, 5, 7, 9])) # Output: 8
Explanation:
1. Core Idea:
The problem can be reduced to identifying all upward trends in the price sequence.
For every increase prices[i] > prices[i-1], you can consider buying at prices[i-1] and selling
at prices[i].
2. Algorithm:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/42
Loop through the array from the second element.
For each day, if the price is higher than the previous day, add the difference to the profit.
3. Edge Cases:
If the prices are constantly decreasing, no profit can be made.
If the prices are constantly increasing, sum up all daily differences.
4. Complexity:
Time Complexity: O(N ), where N is the number of days.
Space Complexity: O(1), as we use only a constant amount of extra space.
Raj is working on a project that involves searching for a specific pattern in a given text. He has heard
about the Knuth-Morris-Pratt (KMP) algorithm, which is efficient for string matching, and he decided
to implement it.
Write a program that takes a text and a pattern as input, and then applies the KMP algorithm to find
and print all pattern occurrences within the text.
Input format :
The first line of input consists of the text string txt, representing the main string where the pattern
needs to be searched.
The second line of input consists of the pattern string pat, that Raj wants to find within the text as a
string.
Output format :
If the pattern is found, print "Found pattern at index i", where i is the index of the first occurrence of
the pattern in the text.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/42
Refer to the sample output for the formatting specifications.
Code constraints :
In this scenario, the given test cases will fall under the following constraints:
1 ≤ |txt| ≤ 50
1 ≤ |pat| ≤ 25
Here is the Python implementation of the Knuth-Morris-Pratt (KMP) Algorithm for pattern searching:
python
def compute_lps(pattern):
"""
Computes the Longest Prefix Suffix (LPS) array for the KMP algorithm.
"""
m = len(pattern)
lps = [0] * m
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/42
length = 0 # Length of the previous longest prefix suffix
i = 1
while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
while i < n:
if pattern[j] == text[i]:
i += 1
j += 1
if j == m:
print(f"Found pattern at index {i - j}")
found = True
j = lps[j - 1] # Continue to find other occurrences
if not found:
print("Pattern not found")
Explanation:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/42
3. Output:
For every match, the starting index of the pattern in the text is printed.
If no match is found, it prints `"Pattern not found"`.
Sample Outputs:
Input 1:
plaintext
ABABDABACDABABCABAB
ABABCABAB
Output 1:
plaintext
Input 2:
plaintext
ababcababcabcabc
abc
Output 2:
plaintext
Input 3:
plaintext
ABC
XY
Output 3:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/42
plaintext
Input 4:
plaintext
AABAACAADAABAABA
AABA
Output 4:
plaintext
Problem Statement
You have been given three arrays A, B, and C in sorted format. By comparing all three arrays, pull
the least possible range.
Example:
Input:
Output: (3, 5)
Input format :
The input consists of three lists, a, b, and c, where each list contains a series of integers.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/42
The second set of lines represents the elements of a list a.
The fifth line represents the length of list c, and the sixth set of lines represents the elements of list
c.
Output format :
The output is a pair of two integers representing the minimum range containing at least one
element from each of the three input lists.
To solve this problem, we can use a three-pointer approach to efficiently find the smallest range that
contains at least one element from each of the three sorted arrays. Here's the Python implementation:
python
import sys
# Sample input
print("Test Case 1:")
arr1 = [1, 2, 3, 4, 5, 6]
arr2 = [7, 8, 9, 10, 11, 12, 13, 14]
arr3 = [15, 16, 17, 18, 19]
print(find_min_range(arr1, arr2, arr3)) # Output: (6, 15)
Explanation:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/42
1. Three Pointers:
Use three pointers i, j , and k to traverse through arrays arr1, arr2, and arr3, respectively.
2. Finding the Range:
For each combination of elements pointed to by i, j , and k , calculate:
\text{min_val}: The smallest value among the three elements.
\text{max_val}: The largest value among the three elements.
The range is [\text{min_val}, \text{max_val}].
3. Updating the Minimum Range:
If the current range is smaller than the previously found minimum range, update the
minimum range and store \text{min_val} and \text{max_val}.
4. Advancing the Pointer:
Move the pointer of the array with the smallest value since increasing the smallest value has
the potential to reduce the range.
5. Termination:
The loop continues until one of the pointers reaches the end of its array.
Complexity:
Time Complexity: O(N ), where N is the total number of elements in the three arrays (assuming
the arrays are roughly equal in size).
Space Complexity: O(1), as no additional space is used.
Input 1:
plaintext
arr1 = [1, 2, 3, 4, 5, 6]
arr2 = [7, 8, 9, 10, 11, 12, 13, 14]
arr3 = [15, 16, 17, 18, 19]
Output 1:
plaintext
(6, 15)
Input 2:
plaintext
Output 2:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/42
plaintext
(3, 5)
Problem Statement
You are given an array of integers. Your task is to find the longest subarray in which the elements
are first sorted in increasing order and then in decreasing order. A subarray is defined as a
contiguous sequence of elements from the original array. Your program should output the length of
this bitonic subarray and the elements it contains.
Input format :
The first line of the input is the size of the array, N.
The second line of the input consists of an array of elements separated by space.
Output format :
The first line displays an integer representing the length of the longest bitonic subarray.
The second line displays the elements of the longest bitonic subarray, separated by a space.
Code constraints :
1 ≤ N ≤ 105
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/42
Here’s the Python implementation to solve the problem of finding the longest bitonic subarray:
python
def find_longest_bitonic_subarray(arr):
n = len(arr)
if n == 0:
return 0, []
Explanation:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/42
At each index i, the bitonic subarray length is given by: \text{bitonic_length} = \text{inc}[i] +
\text{dec}[i] - 1
Subtract 1 because the peak element is counted in both increasing and decreasing subarrays.
4. Finding the Longest Bitonic Subarray:
Iterate through all indices to find the maximum bitonic length and track the start and end
indices of the subarray.
5. Extract the Subarray:
Use the start and end indices to extract the elements of the longest bitonic subarray.
Complexity:
Sample Outputs:
Input 1:
plaintext
7
-4 5 6 8 9 7 -5
Output 1:
plaintext
7
-4 5 6 8 9 7 -5
Input 2:
plaintext
8
1 3 5 2 4 6 3 2
Output 2:
plaintext
5
2 4 6 3 2
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/42
Problem Statement
Assume you are the big boss, and you need to choose the house captain for this week, but in a
mathematical way with some sieving techniques applied.
You have given the contestants a number starting at one and asked them to stand in increasing
order.
In the first round, starting from left to right, remove the first number and every alternate number till
the end of the list.
In the second round, repeat the previous step again, but this time, from right to left, remove the
rightmost number and every alternate number from the list.
Keep repeating the steps again, alternating from left to right and from right to left, until only one
number remains.
Given the integer n, which represents the number of housemates, write a code to return the
number of the contestant who lasts in this and is going to be the house captain this week.
Example
Input:
n=9
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/42
Explanation:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr = [2, 4, 6, 8]
arr = [2, 6]
arr = [6]
Input format :
The input consists of an integer representing the number of housemates n.
Output format :
The output prints an integer, representing the number of the contestant who will be the week's
captain.
Code constraints :
1 ≤ n ≤ 200
python
def house_captain(n):
arr = list(range(1, n + 1)) # Create a list of contestants from 1 to n
left_to_right = True # Start by removing from left to right
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/42
# Sample test cases
print("Test Case 1:")
n1 = 9
print(house_captain(n1)) # Output: 6
Explanation:
1. Initialization:
Start with a list of integers from 1 to n, representing the contestants.
2. Sieving Process:
Alternate between removing every other element from:
Left to right: Start from index 1 and take every second element (arr[1::2]).
Right to left: Reverse the array, remove alternate elements, then reverse it back.
3. Toggle Direction:
Use a boolean variable `left_to_right` to track the direction of removal and toggle it after
each round.
4. Termination:
The process continues until only one element remains in the list.
5. Return Result:
The last remaining element in the list is the house captain.
Complexity:
Sample Outputs:
Input 1:
plaintext
Output 1:
plaintext
Input 2:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/42
plaintext
15
Output 2:
plaintext
Problem Statement
For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10",
"-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers:
["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/42
Input format :
The input consists of a string s.
Output format :
The output displays either "true" or "false" depending on whether the input string represents a valid
number or not.
Code constraints :
The string s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+',
minus '-', or dot '.' with at most 20 characters.
Here is the Python implementation to determine whether a string s represents a valid number based on
the described rules:
python
import re
def is_valid_number(s):
# Regular expression for a valid number
number_regex = r'^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$'
# Check if the input matches the regular expression
return bool(re.match(number_regex, s))
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/42
print(is_valid_number(s3)) # Output: false
Explanation:
1. Regular Expression:
Optional Sign: `^[+-]?`
The number can optionally start with a `+` or `-`.
Decimal or Integer:
Integer: `\d+`
Decimal: `\d+(\.\d*)?` (e.g., `12.`, `12.34`) or `\.\d+` (e.g., `.34`).
Scientific Notation:
`(e|E)` followed by an optional sign (`[+-]?`) and one or more digits (`\d+`).
Combined Pattern:
`^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$`
The `^` and `$` ensure that the entire string matches the pattern.
2. Implementation:
Use Python's `re.match` function to check if the input string matches the pattern.
3. Edge Cases:
Valid numbers: `"2"`, `"-90E3"`, `"3e+7"`, `"-.9"`.
Invalid numbers: `"abc"`, `"e"`, `"1e"`, `"."`.
Complexity:
Time Complexity: O(n), where n is the length of the string s, as regular expression matching
traverses the string once.
Space Complexity: O(1), as no additional data structures are used.
Sample Outputs:
Input 1:
plaintext
Output 1:
plaintext
true
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/42
Input 2:
plaintext
Output 2:
plaintext
false
Input 3:
plaintext
Output 3:
plaintext
false
Problem Statement
Rajesh has given you a string S of size N(where N is divisible by 4), composed of the letters A, C, T,
and G. It is considered to be steady if each of the four letters occurs exactly n/4 times.
You should examine the string S. It is not necessarily steady. Fortunately, You can choose one
(maybe empty) substring and replace it with any string of the same length. Modifying a large
substring should be avoided.
Given a string S, your task is to find the length of the smallest possible substring that can be
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/42
replaced to make a steady string.
Input format :
The first line of input consists of an integer, N denoting the size of the string.
Output format :
The output prints the length of the minimum length substring that can be replaced to make the
string S stable.
Code constraints :
4 <= N <= 100
Here's the Python solution to find the length of the smallest substring that can be replaced to make the
string steady:
python
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 25/42
left += 1
return min_length
Explanation:
1. Frequency Calculation:
Compute the frequency of each character (`A`, `C`, `T`, `G`) in the string S using Python's
`collections.Counter`.
2. Check for Steady String:
A string is steady if the frequency of each character is less than or equal to N /4. If the initial
string satisfies this condition, no replacement is needed, and we return 0.
3. Sliding Window Approach:
Use a sliding window to find the smallest substring that can be replaced.
As the window grows from the `right` end, decrease the frequency of the character at
`right`.
If the remaining string (excluding the window) is steady, calculate the current window's length
and try shrinking the window from the `left` end.
4. Update Minimum Length:
The minimum length of the substring to be replaced is updated when the window represents
a valid solution.
Complexity:
Time Complexity: O(n), as each character is processed at most twice (once when expanding the
window, and once when shrinking it).
Space Complexity: O(1), since the frequency counter uses constant space for four characters.
Sample Outputs:
Input 1:
plaintext
8
GAAATAAA
Output 1:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 26/42
plaintext
Input 2:
plaintext
4
AGAC
Output 2:
plaintext
Problem Statement
Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.
Example 1
Input:
0 -1 2 -3 1
Output:
-1 0 1
-3 2 1
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 27/42
Explanation:
Example 2
Input:
12345
Output:
No Triplet Found
In simply way
python
def find_triplets(arr):
# Sort the array first
arr.sort()
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 28/42
right -= 1
Explanation:
1. Sorting:
We first sort the array. Sorting helps us efficiently find triplets using the two-pointer
technique.
2. Two-pointer Technique:
For each element `arr[i]`, we use two pointers: one (`left`) starts just after `i`, and the
other (`right`) starts at the end of the array.
We check the sum of `arr[i] + arr[left] + arr[right]`. If the sum is zero, we found a valid
triplet.
If the sum is less than zero, we move the `left` pointer to the right to increase the sum.
If the sum is greater than zero, we move the `right` pointer to the left to decrease the sum.
3. Skipping Duplicates:
To avoid counting duplicate triplets, we skip duplicate values by checking the previous
element after finding a valid triplet or moving the pointers.
4. Edge Case:
If no triplet is found, we print `"No Triplet Found"`.
Complexity:
Time Complexity: O(n2 ), where n is the number of elements in the array. Sorting the array takes
O(n log n), and the two-pointer traversal takes O(n) for each element.
Space Complexity: O(1) if we don't count the space used by the input array.
Sample Outputs:
Test Case 1:
Input:
plaintext
5
0 -1 2 -3 1
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 29/42
Output:
plaintext
-1 0 1
-3 2 1
Test Case 2:
Input:
plaintext
5
1 2 3 4 5
Output:
plaintext
No Triplet Found
Problem Statement
In a competitive gardening contest, participants are provided with a list of plant heights represented
as positive numbers in a single-line array, each value separated by spaces. The task at hand is to
identify the most significant difference in height between any two plants. The challenge is to select a
pair of plants, denoted as (i, j). The subtracted value of i and j should be the maximum when
compared with different values of i and j in the array, and also the value of j should be greater than
the value of i.
Example
Input:
10
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 30/42
2
12
Output:
Explanation:
The difference between the values 0 and 5 is 5. If i = 0 and j = 5, It also satisfies the other condition j
> i.
Input format :
The first line contains a single integer n, which represents the number of integers in the list.
The second line contains n integers in n lines, which represent the list of elements.
Output format :
The output consists of a single integer, which represents the maximum difference between two
integers in the list such that the larger integer appears after the smaller integer.
To solve this problem, we need to find the maximum difference between two elements in the array such
that the larger element appears after the smaller element. This can be done efficiently by iterating
through the list and keeping track of the minimum value encountered so far. The goal is to maximize the
difference between the current element and the minimum value encountered before it.
Approach:
1. Track the Minimum Value: As we iterate through the list, we will keep track of the minimum value
encountered so far. This ensures that we are always comparing the current element with the
smallest possible element that appears before it.
2. Calculate the Difference: For each element, calculate the difference between the current element
and the minimum value. If this difference is greater than the previously recorded maximum
difference, update the maximum difference.
3. Edge Cases: Ensure that the array has more than one element, as a single element cannot form a
valid pair.
Python Code:
python
return max_diff
Explanation:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 32/42
1. Initialization:
We initialize `min_value` with the first element of the array and set `max_diff` to negative
infinity.
2. Loop Through the Array:
For each element starting from the second element (`i = 1`), calculate the difference
between the current element and the `min_value` so far.
Update `max_diff` with the maximum of its current value and the newly computed difference.
Update `min_value` to the smaller value between the current element and the `min_value`.
3. Return the Result:
The maximum difference is stored in `max_diff`, which is returned at the end.
Complexity:
Time Complexity: O(n), where n is the number of elements in the array. We iterate through the
array only once.
Space Complexity: O(1), since we are using only a few extra variables.
Test Case 1:
Input:
plaintext
8
2
4
6
10
12
8
14
20
Output:
plaintext
Test Case 2:
Input:
plaintext
8
9
10
2
6
7
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 33/42
12
8
1
Output:
plaintext
Explanation of Outputs:
1. In Test Case 1, the maximum difference occurs between 2 (at index 0) and 9 (at index 7), resulting
in a difference of 7.
2. In Test Case 2, the maximum difference occurs between 2 (at index 2) and 7 (at index 4), resulting
in a difference of 5.
This solution is efficient and handles the problem within the given constraints.
Given two strings, word1, and word2, return the minimum number of operations required to
convert word1 to word2.
Insert a character
Delete a character
Replace a character
Example 1
Input:
horse ros
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 34/42
Explanation:
Example 2
Input:
intention execution
Output:
Explanation :
This problem is commonly known as the Edit Distance Problem or Levenshtein Distance. The goal is
to determine the minimum number of operations required to convert one string (word1) into another
string (word2). The operations allowed are:
1. Insert a character
2. Delete a character
3. Replace a character
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 35/42
Approach:
We can use dynamic programming to solve this problem efficiently. The idea is to build a 2D table (or
matrix) where each cell represents the minimum number of operations required to convert a substring
of word1 to a substring of word2.
Let's define a 2D array `dp` where:
`dp[i][j]` represents the minimum number of operations required to convert the first `i`
characters of word1 to the first `j` characters of word2.
The final answer will be in `dp[len(word1)][len(word2)]`.
Transition:
1. If the characters at `word1[i-1]` and `word2[j-1]` are the same, no operation is needed, and
`dp[i][j] = dp[i-1][j-1]`.
2. If the characters are different, you can:
Insert a character: `dp[i][j-1] + 1`
Delete a character: `dp[i-1][j] + 1`
Replace a character: `dp[i-1][j-1] + 1`
Base cases:
`dp[0][j] = j` (It takes `j` insertions to convert an empty string to the first `j` characters of
word2).
`dp[i][0] = i` (It takes `i` deletions to convert the first `i` characters of word1 to an empty
string).
Algorithm:
python
# Base cases: when one string is empty, all operations are either insertions or deletion
s
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 36/42
# Fill the dp table based on the recurrence
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] # No operation needed if characters are the sam
e
else:
dp[i][j] = min(dp[i - 1][j - 1], # Replace
dp[i - 1][j], # Delete
dp[i][j - 1]) + 1 # Insert
1. Initialization:
We first initialize the `dp` table with dimensions `(m+1) x (n+1)` where `m` is the length of
`word1` and `n` is the length of `word2`.
The base cases are filled: `dp[i][0] = i` for all `i` (convert `word1[0..i]` to an empty string),
and `dp[0][j] = j` for all `j` (convert an empty string to `word2[0..j]`).
2. Filling the DP Table:
For each pair of characters `word1[i-1]` and `word2[j-1]`, we check if they are the same. If
they are, no operation is required, so we copy the value from `dp[i-1][j-1]`. If they are
different, we consider the three operations (insert, delete, replace) and take the minimum.
3. Result:
The final result, which is the minimum number of operations, is stored in `dp[m][n]`.
Time Complexity: O(m × n), where `m` and `n` are the lengths of the two input strings. This is
because we fill a table of size (m + 1) × (n + 1) and each cell computation takes constant time.
Space Complexity: O(m × n), due to the storage required for the `dp` table.
1. Test Case 1:
Input:
plaintext
horse
ros
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 37/42
plaintext
2. Test Case 2:
Input:
plaintext
intention
execution
Output:
plaintext
This approach ensures that the problem is solved efficiently even for larger strings, and it handles all
edge cases correctly.
Problem Statement
Given an array of string words and a width maxWidth, format the text such that each line has
exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each
line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on
a line does not divide evenly between words, the empty slots on the left will be assigned more
spaces than the slots on the right.
The last line of text, should be left justified, and no extra space is inserted between words.
Note:
Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 38/42
Example
16
Output
Explanation
"This is an",
"example of text",
"justification. "
Input
16
Output
Explanation
"acknowledgment ",
"shall be "
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 39/42
]
Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified
instead of fully justified.
Note that the second line is also left-justified because it contains only one word.
To solve the problem of text justification, we need to format the words in such a way that they fit into
lines of a specified width (`maxWidth`). Each line must be fully justified, with spaces distributed evenly
between the words.
Steps:
Detailed Explanation:
Approach:
Python Code:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 40/42
python
return result
Explanation:
Time Complexity:
Time Complexity: O(n), where `n` is the number of words. We iterate through the words once,
and for each line, we distribute spaces, which is done in linear time.
Space Complexity: O(n) for storing the result.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 41/42
Edge Cases:
Test Case 1:
python
Output:
plaintext
Test Case 2:
python
Output:
plaintext
This solution efficiently formats the text with the desired justification and handles edge cases properly.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 42/42