Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum moves to reach destination character in a cyclic String
In this problem, we will find the maximum distance from the initial to the final character in the cyclic string.
The basic approach to solve the problem is to find the next closest final character for every initial character and update the maximum distance if required.
Another approach traverses the string in reverse order and keeps track the index of the last final character. When we get an initial character, we measure the distance and update the maximum distance if required.
Problem statement ? We have given an str string containing the 3 characters, and the length equals N. Also, the string is cyclic. Also, we have given an initial and final character. We need to find the maximum distance from the initial character to its closest final character in the cyclic string.
Sample Examples
Input
str = "pqqrr"; initial = 'r', final = 'p';
Output
2
Explanation
If we take the str[3], the closest final character is str[0]. So, the distance is 2 cyclically.
If we take the str[4], the closes final character is str[0]. So, the distance is 1.
We have taken the maximum distance.
Input
str = "pqrpqqppr"; initial = 'p', final = 'r';
Output
5
Explanation
For str[0], the distance to the closest final character is 2.
For str[3], the distance to the closest ?r' is 5.
For str[6], the distance to the closest ?r' is 2.
For str[7], the distance to the closest ?r' is 1.
The maximum distance is 5.
Input
str = "pqr"; initial = 'r', final = 'q';
Output
2
Explanation
The closest ?q' to the r is at a distance of 2 cyclically.
Approach 1
In this approach, we will find the distance between each initial and its closest final character. We will choose the maximum distance as an output.
Algorithm
Step 1 ? Initialize the ?maxDist' variable with 0 to store the maximum distance.
Step 2 ? If the initial and final character is the same, return 0.
Step 3 ? Start traversing the string. If the current character is equal to the ?initial' character, we need to find the next closest ?final' character.
Step 3.1 ? Use the while loop untilstr[q % str_len] is not equal to the ?final' character. Here, q % str_len helps us to find the closest final character cyclically. Also, increment the value of ?q' in each iteration.
Step 3.2 ? If the ?maxDist' variable's value is less than q - p, update the ?maxDist'.
Step 4 ? Return the maxDist value.
Example
Following are the programs to the above approach
#include <stdio.h>
#include <string.h>
// Function to calculate maximum distance between initial and final characters
int maximumDistance(char str[], char initial, char final) {
int str_len = strlen(str);
int maxDist = 0;
// Base case: If initial and final characters are the same, return 0
if (initial == final) {
return 0;
}
// Iterate through the string to find the maximum distance
for (int p = 0; p < str_len; p++) {
if (str[p] == initial) {
int q = p + 1;
// Use a while loop to find the next occurrence of the final character
while (str[q % str_len] != final) {
q++;
}
// Update maxDist with the maximum distance found
maxDist = (q - p) > maxDist ? (q - p) : maxDist;
}
}
return maxDist;
}
int main() {
char str[] = "pqqrr";
char initial = 'r', final = 'p';
// Call the function and print the result
printf("The maximum distance between the initial and final character is %d\n", maximumDistance(str, initial, final));
return 0;
}
Output
The maximum distance between the initial and final character is 2
#include <bits/stdc++.h>
using namespace std;
int maximumDistance(string str, char initial, char final) {
// String length
int str_len = str.size();
int maxDist = 0;
// Base case
if (initial == final) {
return 0;
}
// Find maximum distance
for (int p = 0; p < str_len; p++) {
if (str[p] == initial) {
// Finding the next final character in the cyclic string
int q = p + 1;
while (str[q % str_len] != final) {
q++;
}
// Take the maximum distance
maxDist = max(maxDist, q - p);
}
}
// Final output
return maxDist;
}
int main() {
string str = "pqqrr";
char initial = 'r', final = 'p';
cout << "The maximum distance between the initial and final character is " << maximumDistance(str, initial, final);
return 0;
}
Output
The maximum distance between the initial and final character is 2
public class Main {
public static int maximumDistance(String str, char initial, char finalChar) {
int strLen = str.length();
int maxDist = 0;
// Base case: If initial and final characters are the same, return 0
if (initial == finalChar) {
return 0;
}
// Iterate through the string to find the maximum distance
for (int p = 0; p < strLen; p++) {
if (str.charAt(p) == initial) {
int q = p + 1;
// Use a while loop to find the next occurrence of the final character
while (str.charAt(q % strLen) != finalChar) {
q++;
}
// Update maxDist with the maximum distance found
maxDist = Math.max(maxDist, q - p);
}
}
return maxDist;
}
public static void main(String[] args) {
String str = "pqqrr";
char initial = 'r';
char finalChar = 'p';
// Call the function and print the result
System.out.println("The maximum distance between the initial and final character is " + maximumDistance(str, initial, finalChar));
}
}
Output
The maximum distance between the initial and final character is 2
def maximum_distance(string, initial, final, initistr_len=None):
max_dist = 0
# Base case: If initial and final characters are the same, return 0
if initial == final:
return 0
# Calculate the length of the string
str_len = len(string)
# Iterate through the string to find the maximum distance
for p in range(str_len):
if string[p] == initial:
q = p + 1
# Use a while loop to find the next occurrence of the final character
while string[q % str_len] != final:
q += 1
# Update max_dist with the maximum distance found
max_dist = max(max_dist, q - p)
return max_dist
string = "pqqrr"
initial = 'r'
final = 'p'
# Call the function and print the result
print("The maximum distance between the initial and final character is", maximum_distance(string, initial, final))
Output
The maximum distance between the initial and final character is 2
Time complexity - O(N8N), as we find the next closest final character while traversing the string.
Space complexity - O(1), as we don't use any dynamic space.
Approach 2
In this approach, we will concatenate the string to itself. After that, we will traverse it from the last and keep track of the index of the last final character. When we find the ?initial' character in the string, we take the index difference to get the distance and update the maximum distance if the current distance is greater than the maximum distance.
Algorithm
Step 1 ? Concatenate the ?str' string to itself.
Step 2 ? Initialize the ?maxDist' with 0 and ?f_index' with -1 to store the index of the last final character.
Step 3 ? If the initial and final characters are the same, return 0.
Step 4 ? Start traversing the str string in reverse order.
Step 5 ? If the current character is equal to the initial character, and f_index is not equal to -1, update the maxDist with max(maxDist, f_index - p) value.
Step 6 ? Else, Assign the ?p' value to the ?f_index'.
Step 7 ? At last, return the ?maxDist' variable's value.
Example
Following are the programs to the above approach
#include <stdio.h>
#include <string.h>
// Function to calculate maximum distance between initial and final characters
int maximumDistance(char str[], char initial, char final) {
// String length
int str_len = strlen(str);
// Allocate space for the concatenated string (twice the length of the input string)
char combinedStr[2 * str_len + 1]; // +1 for the null terminator
// Copy the string to itself
strcpy(combinedStr, str);
strcat(combinedStr, str);
int maxDist = 0, f_index = -1;
// Base case: If initial and final characters are the same, return 0
if (initial == final) {
return 0;
}
// Traverse the concatenated string
for (int p = 2 * str_len - 1; p >= 0; p--) {
// If the current character is an initial character, update the distance
if (combinedStr[p] == initial && f_index != -1) {
maxDist = (f_index - p) > maxDist ? (f_index - p) : maxDist;
}
// Update the index of the final character
if (combinedStr[p] == final) {
f_index = p;
}
}
// Final output
return maxDist;
}
int main() {
char str[] = "pqqrr";
char initial = 'r', final = 'p';
printf("The maximum distance between the initial and final character is %d\n", maximumDistance(str, initial, final));
return 0;
}
Output
The maximum distance between the initial and final character is 2
#include <bits/stdc++.h>
using namespace std;
int maximumDistance(string str, char initial, char final) {
// String length
int str_len = str.size();
// To find the next occurrence of a final character in the cyclic string
str += str;
int maxDist = 0, f_index = -1;
// Base case
if (initial == final) {
return 0;
}
// Traverse the string
for (int p = 2 * str_len - 1; p >= 0; p--) {
// If the current character is an initial character, update the distance
if (str[p] == initial && f_index != -1) {
maxDist = max(maxDist, f_index - p);
}
// Update the index of the final character
if (str[p] == final) {
f_index = p;
}
}
// Final output
return maxDist;
}
int main() {
string str = "pqqrr";
char initial = 'r', final = 'p';
cout << "The maximum distance between the initial and final character is " << maximumDistance(str, initial, final);
return 0;
}
Output
The maximum distance between the initial and final character is 2
public class Main {
public static int maximumDistance(String str, char initial, char finalChar) {
// String length
int strLen = str.length();
// To find the next occurrence of a final character in the cyclic string
str += str; // Concatenate the string to itself
int maxDist = 0;
int fIndex = -1;
// Base case: If initial and final characters are the same, return 0
if (initial == finalChar) {
return 0;
}
// Traverse the string in reverse order
for (int p = 2 * strLen - 1; p >= 0; p--) {
// If the current character is an initial character, update the distance
if (str.charAt(p) == initial && fIndex != -1) {
maxDist = Math.max(fIndex - p, maxDist);
}
// Update the index of the final character
if (str.charAt(p) == finalChar) {
fIndex = p;
}
}
// Final output
return maxDist;
}
public static void main(String[] args) {
String str = "pqqrr";
char initial = 'r';
char finalChar = 'p';
System.out.println("The maximum distance between the initial and final character is " + maximumDistance(str, initial, finalChar));
}
}
Output
The maximum distance between the initial and final character is 2
def maximum_distance(string, initial, final):
# String length
str_len = len(string)
# To find the next occurrence of a final character in the cyclic string
string += string # Concatenate the string to itself
max_dist = 0
f_index = -1
# Base case: If initial and final characters are the same, return 0
if initial == final:
return 0
# Traverse the string in reverse order
for p in range(2 * str_len - 1, -1, -1):
# If the current character is an initial character, update the distance
if string[p] == initial and f_index != -1:
max_dist = max(f_index - p, max_dist)
# Update the index of the final character
if string[p] == final:
f_index = p
# Final output
return max_dist
string = "pqqrr"
initial = 'r'
final = 'p'
print("The maximum distance between the initial and final character is", maximum_distance(string, initial, final))
Output
The maximum distance between the initial and final character is 2
Time complexity - O(N) for traversing the string.
Space complexity - O(N) as we append the string to itself.
The first solution traverses the string and finds the next closest whenever the initial character occurs at any index, but the second solution always keeps track of the nearest final character, improving the problem's time complexity.