w3resource

Java Array Exercises: Check whether there is a pair with a specified sum of a given sorted and rotated array

Java Array: Exercise-46 with Solution

Write a Java program to check whether there is a pair with a specified sum of a given sorted and rotated array.

Sample Solution:

Java Code:

public class Main
{
     static boolean sum_pair(int arr_int[], 
                                    int n, int x)
    {
        int k;
        for (k = 0; k < n - 1; k++)
            if (arr_int[k] > arr_int[k+1])
                break;
                 
        int l = (k + 1) % n;                           
                       
        int r = k;                          
      
       while (l != r)
        {
             if (arr_int[l] + arr_int[r] == x)
                  return true;
             if (arr_int[l] + arr_int[r] < x)
                  l = (l + 1) % n;
                   
             else
                  r = (n + r - 1) % n;
        }
        return false;
    }
 
 public static void main (String[] args)
    {
        int arr_int[] = {22, 25, 17, 18, 19, 20};
        int sum = 42;
        int n = arr_int.length;
      
        if (sum_pair(arr_int, n, sum))
            System.out.print("Array has a pair of elements with sum 42.");
        else
            System.out.print("Array has no pair with sum 42.");
    }
}

Sample Output:

                                                                              
Array has a pair of elements with sum 42.

Flowchart:

Flowchart: Check whether there is a pair with a specified sum of a given sorted and rotated array

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to cyclically rotate a given array clockwise by one.
Next: Write a Java program to find the rotation count in a given rotated sorted array of integers.

What is the difficulty level of this exercise?



Java: Tips of the Day

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

Ref: https://bit.ly/3vRuIPY