Open In App
Related Articles

Check if a Lexicographical Pythagorean Triplets exists in range [0, K) of lexicographically largest string

Improve Article
Improve
Save Article
Save
Like Article
Like

Given a string str and a positive integer K. The task is to find if there exist a Pythagorean Triples in the first window of size K of a string which have the same characters as str but is largest in lexicographical order

Note: Every character is in lower case and consider the following values for each alphabet to check if there exist Pythagorean triples: a = 1, b = 2,  . . ., y = 25, z = 26. 

A triplet(ch1, ch2, ch3) is called Pythagorean triples if (ch1)2 + (ch2)2 = (ch3)2.

Examples:

Input: str = “abxczde”, K = 4
Output: NO
Explanation: The lexicographically largest string having the same characters is zxedcba. 
The first window of size 4 is “zxed”, which does not contain any such triplet.

Input: str = “abcdef”, K = 4
Output: YES
Explanation: The lexicographically largest string possible is “fedcba”. 
The first window of size 4 has “fedc” which have a triplet (c, d, e) that is Pythagorean.

Input: str = “dce”, K = 2
Output: NO
Explanation: As window size is less than 3, choosing a triple is not possible.

 

Approach: This problem can be solved using Greedy algorithm. Follow the steps below for approach: 

Below is the implementation of the approach:

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check for
// Lexicographical Pythagorean triplet
bool Pythagorean(string s, int k)
{
    // If k is less than 3 no triple possible
    if (k < 3) {
        return false;
    }
 
    // Sort the string in descending order
    sort(s.begin(), s.end(), greater<char>());
 
    // Loop to check Pythagorean triples
    for (int i = 0; i < k - 2; ++i) {
 
        // Variables to define boundary of window
        int r = k - 1;
        int l = i + 1;
 
        // Loop for using two pointer approach
        // to find the other two elements
        while (r > l) {
            int a = pow(s[i] - 'a' + 1, 2);
            int b = pow(s[l] - 'a' + 1, 2);
            int c = pow(s[r] - 'a' + 1, 2);
 
            // If triple is found
            if (a == b + c) {
                return true;
            }
 
            // If 'a' is greater
            else if (a > b + c) {
                r--;
            }
 
            // If 'a' is less
            else
                l++;
        }
    }
 
    // No such triple found
    return false;
}
 
// Driver code
int main()
{
    string str = "abcdef";
    int K = 4;
    bool ans = Pythagorean(str, K);
    if (ans)
        cout << "YES";
    else
        cout << "NO";
    return 0;
}


Java




// Java code to implement the above approach
import java.util.*;
 
public class GFG
{
// Utility function to reverse an array
static void reverse(char[] a)
{
    int i, n = a.length;
    char t;
    for (i = 0; i < n / 2; i++)
    {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
}   
 
// Function to check for
// Lexicographical Pythagorean triplet
static boolean Pythagorean(String str, int k)
{
    // If k is less than 3 no triple possible
    if (k < 3) {
        return false;
    }
 
    // Sort the string in descending order
    char[] s = str.toCharArray();
    Arrays.sort(s);
    reverse(s);
 
    // Loop to check Pythagorean triples
    for (int i = 0; i < k - 2; ++i) {
 
        // Variables to define boundary of window
        int r = k - 1;
        int l = i + 1;
 
        // Loop for using two pointer approach
        // to find the other two elements
        while (r > l) {
            int a = (int)Math.pow(s[i] - 'a' + 1, 2);
            int b = (int)Math.pow(s[l] - 'a' + 1, 2);
            int c = (int)Math.pow(s[r] - 'a' + 1, 2);
 
            // If triple is found
            if (a == b + c) {
                return true;
            }
 
            // If 'a' is greater
            else if (a > b + c) {
                r--;
            }
 
            // If 'a' is less
            else
                l++;
        }
    }
 
    // No such triple found
    return false;
}
 
// Driver code
public static void main(String args[])
{
    String str = "abcdef";
    int K = 4;
    boolean ans = Pythagorean(str, K);
    if (ans)
        System.out.println("YES");
    else
        System.out.println("NO");
}
}
// This code is contributed by Samim Hossain Mondal.


Python3




# Python Program to implement
# the above approach
 
# Function to check for
# Lexicographical Pythagorean triplet
def Pythagorean(st, k):
 
    # If k is less than 3 no triple possible
    if (k < 3):
        return False
 
    # Sort the string in descending order
    s = []
    for i in range(len(st)):
         s.append(st[i])
    s.sort()
    s.reverse()
 
    # Loop to check Pythagorean triples
    for i in range(k - 2):
        # Variables to define boundary of window
        r = k - 1
        l = i + 1
 
        # Loop for using two pointer approach
        # to find the other two elements
        while (r > l):
            a = pow(ord(s[i]) - ord('a') + 1, 2)
            b = pow(ord(s[l]) - ord('a') + 1, 2)
            c = pow(ord(s[r]) - ord('a') + 1, 2)
             
            # If triple is found
            if (a == b + c):
                return True
             
 
            # If 'a' is greater
            elif (a > b + c) :
                r -= 1
 
            # If 'a' is less
            else:
                l += 1
         
     
    # No such triple found
    return False
 
# Driver code
str = "abcdef"
K = 4
ans = Pythagorean(str, K)
if (ans):
    print("YES")
else:
    print("NO")
 
# This code is contributed by gfgking


C#




// C# code to implement the above approach
using System;
 
public class GFG
{
// Utility function to reverse an array
static void reverse(char[] a)
{
    int i, n = a.Length;
    char t;
    for (i = 0; i < n / 2; i++)
    {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
}   
 
// Function to check for
// Lexicographical Pythagorean triplet
static bool Pythagorean(string str, int k)
{
    // If k is less than 3 no triple possible
    if (k < 3) {
        return false;
    }
 
    // Sort the string in descending order
    char[] s = str.ToCharArray();
    Array.Sort(s);
    reverse(s);
 
    // Loop to check Pythagorean triples
    for (int i = 0; i < k - 2; ++i) {
 
        // Variables to define boundary of window
        int r = k - 1;
        int l = i + 1;
 
        // Loop for using two pointer approach
        // to find the other two elements
        while (r > l) {
            int a = (int)Math.Pow(s[i] - 'a' + 1, 2);
            int b = (int)Math.Pow(s[l] - 'a' + 1, 2);
            int c = (int)Math.Pow(s[r] - 'a' + 1, 2);
 
            // If triple is found
            if (a == b + c) {
                return true;
            }
 
            // If 'a' is greater
            else if (a > b + c) {
                r--;
            }
 
            // If 'a' is less
            else
                l++;
        }
    }
 
    // No such triple found
    return false;
}
 
// Driver code
public static void Main()
{
    string str = "abcdef";
    int K = 4;
    bool ans = Pythagorean(str, K);
    if (ans)
        Console.Write("YES");
    else
        Console.Write("NO");
}
}
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
 
      // JavaScript Program to implement
      // the above approach
 
      // Function to check for
      // Lexicographical Pythagorean triplet
      function Pythagorean(st, k)
      {
       
          // If k is less than 3 no triple possible
          if (k < 3) {
              return false;
          }
 
          // Sort the string in descending order
          s = [];
          for (let i = 0; i < st.length; i++) { s.push(st.charAt(i)); }
          s.sort(function (a, b) { return b.charCodeAt(0) - a.charCodeAt(0) })
 
          // Loop to check Pythagorean triples
          for (let i = 0; i < k - 2; ++i) {
 
              // Variables to define boundary of window
              let r = k - 1;
              let l = i + 1;
 
              // Loop for using two pointer approach
              // to find the other two elements
              while (r > l) {
                  let a = Math.pow(s[i].charCodeAt(0) - 'a'.charCodeAt(0) + 1, 2);
                  let b = Math.pow(s[l].charCodeAt(0) - 'a'.charCodeAt(0) + 1, 2);
                  let c = Math.pow(s[r].charCodeAt(0) - 'a'.charCodeAt(0) + 1, 2);
                  5
                  // If triple is found
                  if (a == b + c) {
                      return true;
                  }
 
                  // If 'a' is greater
                  else if (a > b + c) {
                      r--;
                  }
 
                  // If 'a' is less
                  else
                      l++;
              }
          }
 
          // No such triple found
          return false;
      }
 
      // Driver code
      let str = "abcdef";
      let K = 4;
      let ans = Pythagorean(str, K);
      if (ans)
          document.write("YES");
      else
          document.write("NO");
 
  // This code is contributed by Potta Lokesh
  </script>


Output

YES

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


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 14 Jan, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials