String character swap problem
Last Updated :
15 Sep, 2023
Given a string S of length N consisting of characters 'L' (sees every character lying to its left) or 'R' (sees every character lying to its right). In one operation, any two consecutive characters can be swapped. The operation can be performed at most once. Determine whether or not each character is being seen by at least one character. Print -1 if it is impossible, 0 if no swap is needed, or the index (1 - indexed) of the first friend if a swap is needed. Note: A character cannot see itself.
Examples:
Input: N = 2, S = "LL"
Output: -1
Explanation: It is impossible even after swapping the two.
Input: N = 2, S = "LR"
Output: 1
Explanation: It is necessary to swap friends 1 and 2. The string becomes "RL". Friend 1 is looking at friend 2 and friend 2 is looking at friend 1.
Input: N = 2, S = "RL"
Output: 0
Explanation: Every friend is already being seen. No swap is needed.
Approach: This can be solved with the following idea:
- If there is an index i such that si = R and si+1 = L, then friend i will see friends i+1, i+2, …, n, and friend i+1 will see 1, 2, …, i. In this case, if L appears right after some R, then all friends are already seen. Therefore, strings like LLRRLL, LRLRLR, RRRLLL, etc. do not require any further operations.
- However, if there is no such index i, we need to perform an operation to see all the friends. We can do this by transforming LR to RL if it appears in the string since we have already concluded that all friends are seen in that case.
- An edge case arises when L and R are never adjacent (neither LR nor RL appears). In this case, si = si+1 must hold for i=1, 2, …, n−1, which means that LL…L and RR…R are the only impossible strings for which the answer is -1.
Steps involved in the implementation of code:
- Initialize Boolean variables 'left', 'right', and 'check' to false.
- Loop through the characters of the string 's' from 'left' to 'right'. For each character, if it is 'L', set 'left' to true, set 'ind' to the index of the character plus one, and if 'right' is also true, set 'check' to true. If the character is 'R', set right to true.
- After looping through the string 's', check the value of 'check'. If it is true, output 0 and exit the function.
- Otherwise output '-1' and exit the function.
Below is the implementation of the code:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function to check whether swap is
// needed or not
void left_right(string s, int n)
{
// Initialize boolean variables
bool left = 0, right = 0, check = 0;
// Initialize index to -1
int ind = -1;
// Loop through string s
for (int i = 0; i < n; i++) {
// If character is L
if (s[i] == 'L') {
// Set left to true
left = 1;
// Set index to current
// index + 1
ind = i + 1;
// If right is also true,
// set check to true
if (right)
check = 1;
}
// If character is R
else
right = 1;
}
// If there are consecutive L and
// R characters, output 0
if (check)
cout << 0 << endl;
else
cout << ind << endl;
}
// Driver Code
int main()
{
// Sample inputs
int n = 5;
string s = "RRLRL";
// Function call
left_right(s, n);
return 0;
}
Java
// Nikunj Sonigara
public class GFG {
// Function to check whether swap is needed or not
static void left_right(String s, int n) {
// Initialize boolean variables
boolean left = false, right = false, check = false;
// Initialize index to -1
int ind = -1;
// Loop through string s
for (int i = 0; i < n; i++) {
// If character is L
if (s.charAt(i) == 'L') {
// Set left to true
left = true;
// Set index to current index + 1
ind = i + 1;
// If right is also true, set check to true
if (right)
check = true;
}
// If character is R
else
right = true;
}
// If there are consecutive L and R characters, output 0
if (check)
System.out.println(0);
else
System.out.println(ind);
}
// Driver Code
public static void main(String[] args) {
// Sample inputs
int n = 5;
String s = "RRLRL";
// Function call
left_right(s, n);
}
}
Python3
def left_right(s, n):
left = False
right = False
check = False
ind = -1
for i in range(n):
if s[i] == 'L':
left = True
ind = i + 1
if right:
check = True
else:
right = True
if check:
print(0)
else:
print(ind)
n = 5
s = "RRLRL"
left_right(s, n)
C#
// C# Implementation
using System;
public class GFG
{
// Function to check whether swap is needed or not
static void left_right(string s, int n)
{
// Initialize boolean variables
bool right = false, check = false;
// Initialize index to -1
int ind = -1;
// Loop through string s
for (int i = 0; i < n; i++)
{
// If character is L
if (s[i] == 'L')
{
// Set left to true
// left = true;
// Set index to current index + 1
ind = i + 1;
// If right is also true, set check to true
if (right)
check = true;
}
// If character is R
else
right = true;
}
// If there are consecutive L and R characters, output 0
if (check)
Console.WriteLine(0);
else
Console.WriteLine(ind);
}
// Driver Code
public static void Main(string[] args)
{
// Sample inputs
int n = 5;
string s = "RRLRL";
// Function call
left_right(s, n);
}
}
// This code is contributed by Sakshi
JavaScript
function left_right(s, n) {
let left = false;
let right = false;
let check = false;
let ind = -1;
for (let i = 0; i < n; i++) {
if (s[i] === 'L') {
left = true;
ind = i + 1;
if (right) {
check = true;
}
} else {
right = true;
}
}
if (check) {
console.log(0);
} else {
console.log(ind);
}
}
const n = 5;
const s = "RRLRL";
left_right(s, n);
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Swap characters in a String Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
14 min read
Swapping Characters of a String in Java As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.In this article we would go through some m
3 min read
Mirror characters of a string Given a string s and an integer k. The task is to perform a mirror transformation on the substring starting from the k-th position to the end of the string. In this transformation, each letter is replaced by its corresponding mirrored letter in the English alphabet ('a' -> 'z', 'b' -> 'y', 'c'
6 min read
String conversion by swapping adjacent characters Given two strings, A and B, both consisting of uppercase alphabets. You can perform the following operation any number of times: choose any index i in string A and swap A[i] with either A[i+k] or A[i+k+1], where k is a positive integer, the task is to determine if it is possible to convert string A
8 min read
Palindrome by swapping only one character Given a string, the task is to check if the string can be made palindrome by swapping a character only once. [NOTE: only one swap and only one character should be swapped with another character] Examples: Input : bbg Output : true Explanation: Swap b(1st index) with g. Input : bdababd Output : true
9 min read