Saturday, October 14, 2023
HomeSoftware DevelopmentVerify if there exists any subarray with the given situations

Verify if there exists any subarray with the given situations


Given two integers N and X. Then the duty is to return YES or NO by checking whether or not there exists a subarray in any permutation of size N such that it comprises a subarray, the place A*B is the same as the X. Right here A and B denote the variety of components in sub-array and the primary aspect of sorted subarray respectively.

Examples:

Enter: N = 5, X = 3
Output: YES
Clarification: Thought of the permutation is: {5, 2, 1, 3, 4}. Take the sub-array {A4. . . .A4} = { 3 }. Then A = 1 (As only one aspect is there), B = 3 (If the sub-array is sorted then first aspect of that sub-array can be 3). So, A * B = 1 * 3 = 3, Which is the same as Y. Subsequently, output is YES.

Enter: N = 7, X = 56
Output: NO
Clarification: It may be verified that no permutation of size N exists such that, It offers worth of A * B as 56. Subsequently, output is NO.

Strategy: To resolve the issue observe the beneath thought:

The issue is predicated on Grasping logic and commentary primarily based. It may be solved by implementing these observations by implementing them in a code. The commentary is, there’ll certainly exist a subarray if the situation (X % i == 0 && (X / i) ≥ 1 && (( X /  i) ≤ N – i + 1) efficiently meet, the place i is the present aspect.

Beneath are the steps for the above method:

  • Create a Boolean Flag and mark it as False initially.  
  • Run a for loop from i = 1 to i ≤ N and observe the below-mentioned steps underneath the scope of the loop:
    •  If (X % i == 0 && (X / i) ≥ 1 && (( X /  i) ≤ N – i + 1)  is true then mark the flag as true and break the loop.
  • Verify if the flag is true, print YES else, print NO.

Beneath is the code to implement the method:

Java

import java.util.*;

  

public class GFG {

  

    

    public static void foremost(String[] args)

    {

  

        

        int N = 5;

        lengthy X = 3;

        Boolean Flag = false;

  

        

        SubArrayExists(N, X, Flag);

    }

  

    

    

    static void SubArrayExists(int N, lengthy X, boolean Flag)

    {

  

        

        

        for (int i = 1; i <= N; i++) {

  

            

            if (X % i == 0 && (X / i) >= 1

                && ((X / i) <= N - i + 1)) {

  

                

                

                Flag = true;

                break;

            }

        }

  

        System.out.println(Flag ? "YES" : "NO");

    }

}

Time Complexity: O(N)
Auxiliary House: O(1), As no further area is used.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments