Similar Problems
Similar Problems not available
Rearrange Characters To Make Target String - Leetcode Solution
Companies:
LeetCode: Rearrange Characters To Make Target String Leetcode Solution
Difficulty: Easy
Topics: string hash-table
The problem "Rearrange Characters To Make Target String" on LeetCode requires us to determine whether it is possible to rearrange the characters of a given string s
to form a target string t
. If it is possible, we need to return true; otherwise, we return false.
The approach to solving this problem is to count the frequency of each character in s
and t
and compare them. If the frequency of every character in t
is less than or equal to the frequency of that character in s
, we can rearrange the characters of s
to form t
. Otherwise, it is impossible to form t
from s
.
Let's break down the solution into the following steps:
Step 1: Initialize two frequency arrays freq1
and freq2
of size 26, representing the frequency of characters in s
and t
respectively. Initially, all elements in these arrays would be 0.
Step 2: Traverse the string s
and increase the frequency of each character by 1 in array freq1
.
Step 3: Traverse the string t
and increase the frequency of each character by 1 in array freq2
.
Step 4: Traverse the frequency arrays freq1
and freq2
and compare the frequency of each character. If the frequency of every character in t
is less than or equal to the frequency of that character in s
, return true, meaning it is possible to rearrange the characters of s
to form t
. Otherwise, return false.
Here is the Python code to implement the above approach:
def canConvertString(s: str, t: str, k: int) -> bool:
freq1 = [0] * 26
freq2 = [0] * 26
if len(s) != len(t):
return False
for i in range(len(s)):
diff = (ord(t[i]) - ord(s[i])) % 26
if diff != 0:
if freq1[diff] + 26 * freq2[diff] > k - diff:
return False
freq1[diff] += 1
return True
As you can see, in addition to the above approach, we also check whether we can form t
from s
using only k operations, where an operation is defined as adding or subtracting 26 from a character's ASCII value. If we cannot form t
using exactly k operations, we return false.
In the code above, we compute the difference between the ASCII values of the corresponding characters in s
and t
. Then, we use this difference to update freq1
and freq2
arrays. Finally, we check whether we can rearrange the characters of s
to form t
using k operations. If it is possible, we return true; otherwise, we return false.
Overall, the time complexity of this approach is O(n), where n is the length of the string s
. The space complexity is O(1) because the frequency arrays have a fixed size of 26.
Rearrange Characters To Make Target String Solution Code
1