Open In App

String character swap problem

Last Updated : 15 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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);


Output

0





Time Complexity: O(N)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads