Open In App

Count of character pairs at same distance as in English alphabets

Last Updated : 12 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, the task is to count the number of pairs whose elements are at the same distances as in the English alphabet. 
Note : Absolute distance between characters is considered.

Examples : 

Input:  str = "geeksforgeeks"
Output:  4
Explanation: In this (g, s), (e, g), (e, k), (e, g) 
are the pairs that are at same distances as
in English alphabets.

Input:  str = "observation"
Output:  4
Explanation: (b, i), (s, v), (o, n), (v, t) are 
at same distances as in English alphabets.

A simple solution is to consider generating all pairs and comparing pair characters with the distance between them. If distance is same for a pair, then increment result. 

Algorithm:

  • Step 1: Take an input string
  • Step 2: Initialize result equals to 0 and n to the length of the string.
  • Step 3: Using nested for loops check if the distance between characters is same
  • Step 4: If distance is same increment the counter (result).
  • Step 5: Print the output.

Below is the implementation of the above algorithm:

C++




// A Simple C++ program to find pairs with distance
// equal to English alphabet distance
#include <bits/stdc++.h>
using namespace std;
 
// Function to count pairs
int countPairs(string str)
{
    int result = 0;
    int n = str.length();
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
 
            // Increment count if characters are at
            // same distance
            if (abs(str[i] - str[j]) == abs(i - j))
                result++;
 
    return result;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    cout << countPairs(str);
    return 0;
}


Java




// A Simple Java program to find pairs with distance
// equal to English alphabet distance
import java.io.*;
class Test {
     
    // Method to count pairs
    static int countPairs(String str)
    {
        int result = 0;
        int n = str.length();
        for (int i = 0; i < n; i++)
          for (int j = i + 1; j < n; j++)
             
            // Increment count if characters
            // are at same distance
            if (Math.abs(str.charAt(i) - str.charAt(j)) ==
                                          Math.abs(i - j))
                result++;
 
        return result;
    }
 
    // Driver method
    public static void main(String args[])
    {
        String str = "geeksforgeeks";
        System.out.println(countPairs(str));
    }
}


Python 3




# Simple Python3 program to find pairs with
# distance equal to English alphabet distance
 
# Function to count pairs
def countPairs(str1):
    result = 0;
    n = len(str1)
    for i in range(0, n):
        for j in range(i + 1, n):
 
            # Increment count if characters
            # are at same distance
            if (abs(ord(str1[i]) -
                    ord(str1[j])) == abs(i - j)):
                result += 1;
 
    return result;
 
# Driver code
if __name__ == "__main__":
    str1 = "geeksforgeeks";
    print(countPairs(str1));
 
# This code is contributed
# by Sairahul099


C#




// A Simple C# program to find pairs with distance
// equal to English alphabet distance
using System;
 
class Test {
     
    // Method to count pairs
    static int countPairs(string str)
    {
        int result = 0;
        int n = str.Length;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
             
            // Increment count if characters
            // are at same distance
            if (Math.Abs(str[i] - str[j]) == Math.Abs(i - j))
                result++;
 
        return result;
    }
 
    // Driver method
    public static void Main()
    {
        string str = "geeksforgeeks";
        Console.WriteLine(countPairs(str));
    }
}
 
// This Code is contributed by vt_m.


PHP




<?php
// PHP program for Count
// of character pairs at
// same distance as in
// English alphabets
 
// Function to count pairs
function countPairs($str)
{
    $result = 0;
    $n = strlen($str);
    for ($i = 0; $i < $n; $i++)
        for ($j = $i + 1;
             $j < $n; $j++)
 
            // Increment count if
            // characters are at
            // same distance
            if (abs(ord($str[$i]) -
                    ord($str[$j])) ==
                    abs($i - $j))
                $result++;
 
    return $result;
}
 
// Driver code
$str = "geeksforgeeks";
echo countPairs($str);
 
// This code is contributed by Sam007
?>


Javascript




<script>
    // A Simple Javascript program to find pairs with distance
    // equal to English alphabet distance
     
    // Method to count pairs
    function countPairs(str)
    {
        let result = 0;
        let n = str.length;
        for (let i = 0; i < n; i++)
            for (let j = i + 1; j < n; j++)
               
            // Increment count if characters
            // are at same distance
            if (Math.abs(str[i].charCodeAt() - str[j].charCodeAt()) == Math.abs(i - j))
                result++;
   
        return result;
    }
     
    let str = "geeksforgeeks";
      document.write(countPairs(str));
    
   // This code is contributed by divyesh072019.
</script>


Output

4

Time complexity: O(n2). The above method can be optimized by using the fact that there can be only 26 alphabets i.e. instead of checking an element up to length of string, check only from current index to 26th index.
Auxiliary Space: O(n), where n is the length of string. This is because when string is passed to any function it is passed by value and creates a copy of itself in stack. 

C++




// An optimized C++ program to find pairs with distance
// equal to English alphabet distance
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
 
// Function to count pairs with distance
// equal to English alphabet distance
int countPairs(string str)
{
    int result = 0;
    int n = str.length();
 
    for (int i = 0; i < n; i++)
 
        // This loop runs at most 26 times
        for (int j = 1; (i + j) < n && j <= MAX_CHAR; j++)
            if ((abs(str[i + j] - str[i]) == j))
                result++;
 
    return result;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    cout << countPairs(str);
    return 0;
}


Java




// An optimized Java program to find pairs with distance
// equal to English alphabet distance
import java.io.*;
class Test {
    static final int MAX_CHAR = 26;
 
    // Method to count pairs with distance
    // equal to English alphabet distance
    static int countPairs(String str)
    {
        int result = 0;
        int n = str.length();
 
        for (int i = 0; i < n; i++)
 
            // This loop runs at most 26 times
            for (int j = 1; (i + j) < n && j <= MAX_CHAR; j++)
                if ((Math.abs(str.charAt(i + j) - str.charAt(i)) == j))
                    result++;
 
        return result;
    }
 
    // Driver method
    public static void main(String args[])
    {
        String str = "geeksforgeeks";
        System.out.println(countPairs(str));
    }
}


Python 3




# An optimized C++ program to find pairs with
# distance equal to English alphabet distance
 
MAX_CHAR = 26
 
# Function to count pairs with distance
# equal to English alphabet distance
def countPairs(str1):
    result = 0;
    n = len(str1)
 
    for i in range(0, n):
 
        # This loop runs at most 26 times
        for j in range(1, MAX_CHAR + 1):
            if((i + j) < n):
                if ((abs(ord(str1[i + j]) -
                         ord(str1[i])) == j)):
                    result += 1;
 
    return result
 
# Driver code
if __name__ == "__main__":
    str1 = "geeksforgeeks";
    print(countPairs(str1))
 
# This code is contributed
# by Sairahul099


C#




// An optimized C# program to find pairs with distance
// equal to English alphabet distance
using System;
 
class Test {
     
    static int MAX_CHAR = 26;
 
    // Method to count pairs with distance
    // equal to English alphabet distance
    static int countPairs(string str)
    {
        int result = 0;
        int n = str.Length;
 
        for (int i = 0; i < n; i++)
 
            // This loop runs at most 26 times
            for (int j = 1; (i + j) < n && j <= MAX_CHAR; j++)
                if ((Math.Abs(str[i + j] - str[i]) == j))
                    result++;
 
        return result;
    }
 
    // Driver method
    public static void Main()
    {
        string str = "geeksforgeeks";
        Console.WriteLine(countPairs(str));
    }
}
 
// This Code is contributed by vt_m.


PHP




<?php
// An optimized PHP program
// to find pairs with distance
// equal to English alphabet distance
 
// Function to count pairs
// with distance equal to
// English alphabet distance
function countPairs($str)
{
    $result = 0;
    $n = strlen($str);
 
    for ($i = 0; $i < $n; $i++)
 
        // This loop runs at
        // most 26 times
        for ($j = 1; ($i + $j) < $n &&
                      $j <= 26; $j++)
            if ((abs(ord($str[$i + $j]) -
                     ord($str[$i]) ) == $j))
                $result++;
 
    return $result;
}
 
// Driver code
$str = "geeksforgeeks";
echo countPairs($str);
 
// This code is contributed by Sam007
?>


Javascript




<script>   
    // An optimized Javascript program to find pairs with distance
    // equal to English alphabet distance
     
    let MAX_CHAR = 26;
  
    // Method to count pairs with distance
    // equal to English alphabet distance
    function countPairs(str)
    {
        let result = 0;
        let n = str.length;
  
        for (let i = 0; i < n; i++)
  
            // This loop runs at most 26 times
            for (let j = 1; (i + j) < n && j <= MAX_CHAR; j++)
                if ((Math.abs(str[i + j].charCodeAt() - str[i].charCodeAt()) == j))
                    result++;
  
        return result;
    }
     
    let str = "geeksforgeeks";
      document.write(countPairs(str));
 
</script>


Output

4

Time complexity: O(n2) under the assumption that alphabet size is constant.
Auxiliary Space: O(n), where n is the length of string. This is because when string is passed to any function it is passed by value and creates a copy of itself in stack. 

 



Similar Reads

Count of ways to rearrange N digits and M alphabets keeping all alphabets together
Given two positive integers N and M representing the count of distinct digits and alphabets respectively in a string, the task to count the number of ways to rearrange the characters of the string such that all the alphabets are adjacent. Examples: Input: N = 2, M = 2Output: 12Explanation: Possible ways to rearrange characters of a string such that
9 min read
Modify string by replacing characters by alphabets whose distance from that character is equal to its frequency
Given a string S consisting of N lowercase alphabets, the task is to modify the string S by replacing each character with the alphabet whose circular distance from the character is equal to the frequency of the character in S. Examples: Input: S = "geeks"Output: hggltExplanation: The following modifications are done on the string S: The frequency o
7 min read
For each lowercase English alphabet find the count of strings having these alphabets
Given an array of strings of lowercase English alphabets. The task is for each letter [a-z] to find the count of strings having these letters.Examples: Input: str = { "geeks", "for", "code" } Output: { 0 0 1 1 2 1 1 0 0 0 0 0 0 0 2 0 0 1 1 0 0 0 0 0 0 0 } Explanation: For a letter, say 'e', it is present in { "geeks", "code" }, hence its count is 2
11 min read
Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
Given string str of size N consists of lower-case English alphabets. The task is to find the arrangement of the characters of the string such that no two adjacent characters are neighbors in English alphabets. In case of multiple answers print any of them. If no such arrangement is possible then print -1.Examples: Input: str = "aabcd" Output: bdaac
6 min read
Longest subsequence with consecutive English alphabets
Given string S, the task is to find the length of the longest subsequence of the consecutive lowercase alphabets. Examples: Input: S = "acbdcfhg"Output: 3Explanation: String "abc" is the longest subsequence of consecutive lowercase alphabets.Therefore, print 3 as it is the length of the subsequence "abc". Input: S = "gabbsdcdggbe"Output: 5 Naive Ap
6 min read
Longest substring with no pair of adjacent characters are adjacent English alphabets
Given a string S consisting of lowercase English alphabets, the task is to find the longest substring from the given string such that no two adjacent characters are neighbouring English alphabets. Examples: Input: S = "aabdml"Output: "bdm"Explanation: Substring "bdm" is the longest substring which satisfies the given condition. Input: S = "abc"Outp
7 min read
Count of strings possible by replacing two consecutive same character with new character
Given string str. The task is to count the number of all different strings possible if two consecutive same characters of the string can be replaced by one different character. Examples Input: str = "abclll" Output: 3 Explanation: There can be 3 different string including the original string as shown in the below figure:- Input: str = "abcllldefkkk
8 min read
Maximise distance by rearranging all duplicates at same distance in given Array
Given an array arr[] of N integers. Arrange the array in a way such that the minimum distance among all pairs of same elements is maximum among all possible arrangements. The task is to find this maximum value. Examples: Input: arr[] = {1, 1, 2, 3}Output: 3Explanation: All possible arrangements are: {1, 1, 2, 3}, {1, 1, 3, 2}, {1, 2, 1, 3}, {1, 2,
6 min read
Count of index pairs (i, j) such that string after deleting ith character is equal to string after deleting jth character
Given a string str of N characters, the task is to calculate the count of valid unordered pairs of (i, j) such that the string after deleting ith character is equal to the string after deleting the jth character. Examples: Input: str = "aabb"Output: 2Explanation: The string after deletion of 1st element is "abb" and the string after deletion of 2nd
6 min read
Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the number of pairs such that the chosen elements are
12 min read
Article Tags :
Practice Tags :