Open In App

Concatenate pairs of lexicographically adjacent characters

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S that contains only lowercase alphabets and no special characters except spaces, the task is to find lexicographically adjacent pairs of characters and concatenate the number of pairs of each word in the string.

Examples:

Input: S = “hello world”
Output: 21
Explanation: Input string contains two words “hello” and “world”, In word ‘hello’, ‘e’ & ‘l’ and ‘l’ & ‘o’ are in lexicographical order so the pair count for “hello” is 2. In word “world” only ‘o’ & ‘r’ are in lexical order so pair count for “world” is 1. On concatenating both result we get 21 as output.

Input: S = “venom vest”
Output: 22
Explanation: Input string contains two words “venom” and “vest”, In word “venom”, ‘e’ & ‘n’ and ‘n’ & ‘o’ are in lexicographical order so the pair count for “venom” is 2. In word “vest”, ‘e’ & ‘s’ and ‘s’ & ‘t’ are in lexical order so pair count for “vest” is 2. On concatenating both result we get 22 as output.

Input: S =abcdefghijklmn mno”
Output: 132
Explanation: Input string contains two words, In first word “abcdefghijklmn”, every single adjacent character follows the lexical order thus there are total 13 pairs and for second word “mno” there are 2 pairs.On concatenating both result we get 132 as output.

Approach: To solve the problem follow the below idea:

The approach is to initially find the number of pairs in every word and then use that pair count for concatenating so this can be done in the below steps:

Steps to follow to solve the problem:

  • Initialize a vector of string to extract words from the input string and then initialize the int vector of size n ( the size of the string vector ) to keep the count of pairs in each word.
  • Use istringstream to extract words from the input string and store every word into a string vector.
  • Iterate over string vector and for every single iteration, perform the operation mentioned below:
    • Take the current word and store it in a temp string and iterate over the temp string and check whether the ASCII values of two adjacent characters follow the lexical order or not. If Yes, then take the pair count value and increment it.
    • Store the pair count in an integer vector.
  • After this initialize an integer variable for the final answer with the first value of the integer vector and then iterate over the vector values for concatenating.

Below is the implementation for the above approach:

C++




// C++ code to implement the approach.
#include <bits/stdc++.h>
using namespace std;
 
// Function to concatenate the required
// count of lexicographically adjacent
// characters.
int concatPairs(string s)
{
    vector<string> ans;
    istringstream s1(s);
 
    // Creating a stream of words
    // separated by space
    string word;
    while (s1 >> word) {
        ans.push_back(word);
    }
    int n = ans.size();
    vector<int> values(n);
    for (int i = 0; i < n; i++) {
        string temp = ans[i];
        int pair = 0;
 
        // Counting number of pairs
        for (int i = 1; i < temp.size(); i++) {
            if (temp[i - 1] - 0 < temp[i] - 0) {
                pair++;
            }
        }
        values[i] = pair;
    }
    int finalAns = values[0];
 
    // Constructing final ans with
    // number of pairs
    for (int i = 1; i < n; i++) {
        finalAns *= 10;
        finalAns += values[i];
    }
    return finalAns;
}
 
// Driver's code
int main()
{
    string s = "abcdefghijklmn mno";
 
    // Function call.
    int finalAns = concatPairs(s);
 
    // Printing final output.
    cout << finalAns;
    return 0;
}


Java




// Java code to implement the approach.
import java.io.*;
import java.util.*;
 
class GFG {
    // Function to concatenate the required
    // count of lexicographically adjacent
    // characters.
    public static int concatPairs(String s)
    {
        s += " ";
        ArrayList<String> ans = new ArrayList<String>();
        int sz = s.length();
        // Creating a stream of words
        // separated by space
        String word = "";
        for (int i = 0; i < sz; i++) {
            if (s.charAt(i) == ' ') {
                ans.add(word);
                word = "";
            }
            else
                word += s.charAt(i);
        }
        int n = ans.size();
        ArrayList<Integer> values
            = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            String temp = ans.get(i);
            int pair = 0;
 
            // Counting number of pairs
            for (int j = 1; j < temp.length(); j++) {
                if (temp.charAt(j - 1) - 0
                    < temp.charAt(j) - 0) {
                    pair++;
                }
            }
            values.add(pair);
        }
 
        int finalAns = values.get(0);
 
        // Constructing final ans with
        // number of pairs
        for (int i = 1; i < n; i++) {
            finalAns *= 10;
            finalAns += values.get(i);
        }
        return finalAns;
    }
 
    // Driver's code
    public static void main(String[] args)
    {
        String s = "abcdefghijklmn mno";
 
        // Function call.
        int finalAns = concatPairs(s);
 
        // Printing final output.
        System.out.print(finalAns);
    }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Function to concatenate the required
# count of lexicographically adjacent
# characters.
def concatPairs(s: str) -> int:
    ans = []
    # Creating a stream of words separated by space
    for word in s.split():
        ans.append(word)
 
    n = len(ans)
    values = [0] * n
    for i in range(n):
        temp = ans[i]
        pair = 0
 
        # Counting number of pairs
        for j in range(1, len(temp)):
            if ord(temp[j-1]) < ord(temp[j]):
                pair += 1
        values[i] = pair
 
    finalAns = values[0]
 
    # Constructing final ans with number of pairs
    for i in range(1, n):
        finalAns *= 10
        finalAns += values[i]
    return finalAns
 
# Driver's code
if __name__ == '__main__':
    s = "abcdefghijklmn mno"
 
    # Function call
    finalAns = concatPairs(s)
 
    # Printing final output
    print(finalAns)


C#




// C# code to implement the approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to concatenate the required count of
    // lexicographically adjacent characters.
    public static int concatPairs(string s)
    {
        s += " ";
        List<string> ans = new List<string>();
        int sz = s.Length;
        // Creating a stream of words separated by space
        string word = "";
        for (int i = 0; i < sz; i++) {
            if (s[i] == ' ') {
                ans.Add(word);
                word = "";
            }
            else
                word += s[i];
        }
        int n = ans.Count;
        List<int> values = new List<int>();
        for (int i = 0; i < n; i++) {
            string temp = ans[i];
            int pair = 0;
 
            // Counting number of pairs
            for (int j = 1; j < temp.Length; j++) {
                if (temp[j - 1] - 0 < temp[j] - 0) {
                    pair++;
                }
            }
            values.Add(pair);
        }
 
        int finalAns = values[0];
 
        // Constructing final ans with number of pairs
        for (int i = 1; i < n; i++) {
            finalAns *= 10;
            finalAns += values[i];
        }
        return finalAns;
    }
 
    static public void Main()
    {
 
        // Code
        string s = "abcdefghijklmn mno";
 
        // Function call.
        int finalAns = concatPairs(s);
 
        // Printing final output.
        Console.Write(finalAns);
    }
}
 
// This code is contributed by sankar.


Javascript




// JavaScript code to implement the approach.
 
// Function to concatenate the required count of
// lexicographically adjacent characters.
function concatPairs(s) {
    s += " ";
    let ans = [];
    let sz = s.length;
    let word = "";
    // Creating an array of words separated by space
    for (let i = 0; i < sz; i++) {
        if (s[i] === " ") {
            ans.push(word);
            word = "";
        }
        else
            word += s[i];
        }
        let n = ans.length;
        let values = [];
        for (let i = 0; i < n; i++) {
        let temp = ans[i];
        let pair = 0;
            // Counting number of pairs
            for (let j = 1; j < temp.length; j++) {
                if (temp.charCodeAt(j - 1) < temp.charCodeAt(j)) {
                    pair++;
            }
        }
        values.push(pair);
    }
 
    let finalAns = values[0];
     
    // Constructing final ans with number of pairs
    for (let i = 1; i < n; i++) {
        finalAns *= 10;
        finalAns += values[i];
    }
    return finalAns;
}
 
let s = "abcdefghijklmn mno";
 
// Function call.
let finalAns = concatPairs(s);
 
// Printing final output.
console.log(finalAns);
 
// This code is contributed by karthik.


Output

132

Time Complexity: O(3N) //First N for iterating over input string for extracting words + Second N for processing every word to find pair + Third N for generating unique code.
Auxiliary Space: O(2N)//First N for storing words in string vector + Second N for storing pair counts in an integer vector



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads