Skip to content
Related Articles

Related Articles

Improve Article
Check if it is possible to reach any point on the circumference of a given circle from origin
  • Difficulty Level : Hard
  • Last Updated : 14 May, 2021

Given a string S representing a sequence of moves(L, R, U, and D) and an integer R representing the radius of a circle whose center is the origin (0, 0), the task is to check if it is possible to reach any point on the circumference of the given circle from the origin by choosing any subsequence of moves from the string S. If it is possible to reach a point on the circumference, then print “Yes”. Otherwise, print “No”
The operations required to be performed for each direction are as follows:

  • If the current character is L, then decrement x-coordinate by 1.
  • If the current character is R, then increment x-coordinate by 1.
  • If the current character is U, then increment y-coordinate by 1.
  • If the current character is D, then decrement y-coordinate by 1.

Examples:

Input: S = “LLRULD”, R = 3
Output: Yes
Explanation: 
Selecting the subsequence “LLL”, the change in coordinates by performing the sequence of moves are:
(0, 0) → ( -1, 0) → (-2, 0) → (-3, 0)
Since (-3, 0) lies on the circumference of the given circle, it is possible to reach the  

Input: S = “ULRDLD”, R = 6
Output: No

Naive Approach: The simplest approach is to generate all possible subsequences of the given string S and if there exists any subsequence of moves that result in reaching the circumference of the circle from the origin (0, 0) then print “Yes”. Otherwise, print “No”.



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

Efficient Approach: The above approach can be optimized based on the below observations:

  • Since the path required to be considered starts from the origin (0, 0), if the maximum count among each of the characters L, R, U, and D, in the string has a value exceeding R, then the path from origin to the circumference of the circle exists.
  • If there exist any two values X and Y such that the sum of squares of X and Y is R2, then there exists a triangular path from origin to the circumference of the circle.

Follow the steps below to solve the given problem:

  • Store the count of characters L, R, U, and D, in the given string S in a variable, say cntL, cntR, cntU, and cntD respectively.
  • If the maximum of cntL, cntR, cntU, and cntD is at least R, then there exists a straight line path from origin to the circumference. Therefore, print “Yes”.
  • If the square of the maximum of cntL and cntR and the maximum of cntU and cntD is at least R2, then print “Yes”, as there exists a triangular path from origin to the circumference of the circle.
  • If none of the above case arises, then print “No”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible
// to reach any point on circumference
// of the given circle from (0,0)
string isPossible(string S, int R, int N)
{
    // Stores the count of 'L', 'R'
    int cntl = 0, cntr = 0;
 
    // Stores the count of 'U', 'D'
    int cntu = 0, cntd = 0;
 
    // Traverse the string S
    for (int i = 0; i < N; i++) {
        // Update the count of L
        if (S[i] == 'L')
            cntl++;
 
        // Update the count of R
        else if (S[i] == 'R')
            cntr++;
 
        // Update the count of U
        else if (S[i] == 'U')
            cntu++;
 
        // Update the count of D
        else
            cntd++;
    }
 
    // Condition 1 for reaching
    // the circumference
    if (max(max(cntl, cntr), max(cntu, cntd)) >= R)
        return "Yes";
 
    unordered_map<int, int> mp;
 
    int r_square = R * R;
 
    for (int i = 1; i * i <= r_square; i++) {
 
        // Store the the value
        // of (i * i) in the Map
        mp[i * i] = i;
 
        // Check if (r_square - i*i)
        // already present in HashMap
        if (mp.find(r_square - i * i) != mp.end()) {
           
            // If it is possible to reach the
            // point (± mp[r_square - i*i], ± i)
            if (max(cntl, cntr)
                >= mp[r_square - i * i]
                && max(cntu, cntd) >= i)
 
                return "Yes";
 
            // If it is possible to reach the
            // point (±i, ±mp[r_square-i*i])
            if (max(cntl, cntr) >= i
                && max(cntu, cntd)
                >= mp[r_square - i * i])
 
                return "Yes";
        }
    }
 
    // If it is impossible to reach
    return "No";
}
 
// Driver Code
int main()
{
    string S = "RDLLDDLDU";
    int R = 5;
    int N = S.length();
   
    cout << isPossible(S, R, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check if it is possible
// to reach any point on circumference
// of the given circle from (0,0)
static String isPossible(String S, int R, int N)
{
     
    // Stores the count of 'L', 'R'
    int cntl = 0, cntr = 0;
 
    // Stores the count of 'U', 'D'
    int cntu = 0, cntd = 0;
 
    // Traverse the string S
    for(int i = 0; i < N; i++)
    {
         
        // Update the count of L
        if (S.charAt(i) == 'L')
            cntl++;
 
        // Update the count of R
        else if (S.charAt(i) == 'R')
            cntr++;
 
        // Update the count of U
        else if (S.charAt(i) == 'U')
            cntu++;
 
        // Update the count of D
        else
            cntd++;
    }
 
    // Condition 1 for reaching
    // the circumference
    if (Math.max(Math.max(cntl, cntr),
                 Math.max(cntu, cntd)) >= R)
        return "Yes";
 
    HashMap<Integer, Integer> mp = new HashMap<>();
 
    int r_square = R * R;
 
    for(int i = 1; i * i <= r_square; i++)
    {
         
        // Store the the value
        // of (i * i) in the Map
        mp.put(i * i, i);
 
        // Check if (r_square - i*i)
        // already present in HashMap
        if (mp.containsKey(r_square - i * i))
        {
             
            // If it is possible to reach the
            // point (± mp[r_square - i*i], ± i)
            if (Math.max(cntl, cntr) >=
                mp.get(r_square - i * i) &&
                Math.max(cntu, cntd) >= i)
                return "Yes";
 
            // If it is possible to reach the
            // point (±i, ±mp[r_square-i*i])
            if (Math.max(cntl, cntr) >= i &&
                Math.max(cntu, cntd) >=
                mp.get(r_square - i * i))
                return "Yes";
        }
    }
 
    // If it is impossible to reach
    return "No";
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "RDLLDDLDU";
    int R = 5;
    int N = S.length();
 
    System.out.println(isPossible(S, R, N));
}
}
 
// This code is contributed by Kingash

Python3




# Python3 program for the above approach
 
# Function to check if it is possible
# to reach any point on circumference
# of the given circle from (0,0)
def isPossible(S, R, N):
 
    # Stores the count of 'L', 'R'
    cntl = 0
    cntr = 0
 
    # Stores the count of 'U', 'D'
    cntu = 0
    cntd = 0
 
    # Traverse the string S
    for i in range(N):
         
        # Update the count of L
        if (S[i] == 'L'):
            cntl += 1
 
        # Update the count of R
        elif (S[i] == 'R'):
            cntr += 1
 
        # Update the count of U
        elif (S[i] == 'U'):
            cntu += 1
 
        # Update the count of D
        else:
            cntd += 1
 
    # Condition 1 for reaching
    # the circumference
    if (max(max(cntl, cntr), max(cntu, cntd)) >= R):
        return "Yes"
 
    mp = {}
 
    r_square = R * R
 
    i = 1
    while i * i <= r_square:
         
        # Store the the value
        # of (i * i) in the Map
        mp[i * i] = i
 
        # Check if (r_square - i*i)
        # already present in HashMap
        if ((r_square - i * i) in mp):
 
            # If it is possible to reach the
            # point (± mp[r_square - i*i], ± i)
            if (max(cntl, cntr) >= mp[r_square - i * i] and
               max(cntu, cntd) >= i):
 
                return "Yes"
 
            # If it is possible to reach the
            # point (±i, ±mp[r_square-i*i])
            if (max(cntl, cntr) >= i and
               max(cntu, cntd) >= mp[r_square - i * i]):
 
                return "Yes"
 
        i += 1
 
    # If it is impossible to reach
    return "No"
 
# Driver Code
if __name__ == "__main__":
 
    S = "RDLLDDLDU"
    R = 5
    N = len(S)
 
    print(isPossible(S, R, N))
 
# This code is contributed by ukasp

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  // Function to check if it is possible
  // to reach any point on circumference
  // of the given circle from (0,0)
  static string isPossible(string S, int R, int N)
  {
 
    // Stores the count of 'L', 'R'
    int cntl = 0, cntr = 0;
 
    // Stores the count of 'U', 'D'
    int cntu = 0, cntd = 0;
 
    // Traverse the string S
    for(int i = 0; i < N; i++)
    {
 
      // Update the count of L
      if (S[i] == 'L')
        cntl++;
 
      // Update the count of R
      else if (S[i] == 'R')
        cntr++;
 
      // Update the count of U
      else if (S[i] == 'U')
        cntu++;
 
      // Update the count of D
      else
        cntd++;
    }
 
    // Condition 1 for reaching
    // the circumference
    if (Math.Max(Math.Max(cntl, cntr),
                 Math.Max(cntu, cntd)) >= R)
      return "Yes";
 
    Dictionary<int, int> mp = new Dictionary<int, int>();
 
    int r_square = R * R;
 
    for(int i = 1; i * i <= r_square; i++)
    {
 
      // Store the the value
      // of (i * i) in the Map
      mp.Add(i * i, i);
 
      // Check if (r_square - i*i)
      // already present in HashMap
      if (mp.ContainsKey(r_square - i * i))
      {
 
        // If it is possible to reach the
        // point (± mp[r_square - i*i], ± i)
        if (Math.Max(cntl, cntr) >=
            mp[r_square - i * i] &&
            Math.Max(cntu, cntd) >= i)
          return "Yes";
 
        // If it is possible to reach the
        // point (±i, ±mp[r_square-i*i])
        if (Math.Max(cntl, cntr) >= i &&
            Math.Max(cntu, cntd) >=
            mp[r_square - i * i])
          return "Yes";
      }
    }
 
    // If it is impossible to reach
    return "No";
  }
  static public void Main ()
  {
    string S = "RDLLDDLDU";
    int R = 5;
    int N = S.Length;
 
    Console.WriteLine(isPossible(S, R, N));
  }
}
 
// This code is contributed by offbeat

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to check if it is possible
// to reach any point on circumference
// of the given circle from (0,0)
function isPossible(S, R, N)
{
    // Stores the count of 'L', 'R'
    var cntl = 0, cntr = 0;
 
    // Stores the count of 'U', 'D'
    var cntu = 0, cntd = 0;
 
    // Traverse the string S
    for (var i = 0; i < N; i++) {
        // Update the count of L
        if (S[i] == 'L')
            cntl++;
 
        // Update the count of R
        else if (S[i] == 'R')
            cntr++;
 
        // Update the count of U
        else if (S[i] == 'U')
            cntu++;
 
        // Update the count of D
        else
            cntd++;
    }
 
    // Condition 1 for reaching
    // the circumference
    if (Math.max(Math.max(cntl, cntr), Math.max(cntu, cntd)) >= R)
        return "Yes";
 
    var mp = new Map();
 
    var r_square = R * R;
 
    for (var i = 1; i * i <= r_square; i++) {
 
        // Store the the value
        // of (i * i) in the Map
        mp.set(i * i, i);
 
        // Check if (r_square - i*i)
        // already present in HashMap
        if (mp.has(r_square - i * i)) {
           
            // If it is possible to reach the
            // point (± mp[r_square - i*i], ± i)
            if (Math.max(cntl, cntr)
                >= mp.get(r_square - i * i)
                && Math.max(cntu, cntd) >= i)
 
                return "Yes";
 
            // If it is possible to reach the
            // point (±i, ±mp[r_square-i*i])
            if (Math.max(cntl, cntr) >= i
                && Math.max(cntu, cntd)
                >= mp.get(r_square - i * i))
 
                return "Yes";
        }
    }
 
    // If it is impossible to reach
    return "No";
}
 
// Driver Code
var S = "RDLLDDLDU";
var R = 5;
var N = S.length;
 
document.write( isPossible(S, R, N));
 
 
</script>
Output: 
Yes

 

Time Complexity: O(N + R)
Auxiliary Space: O(R2)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :