Skip to content

Instantly share code, notes, and snippets.

@summit87
Last active August 12, 2019 19:56
Show Gist options
  • Select an option

  • Save summit87/27ab9b64d4d5558feecf9760e89eacd6 to your computer and use it in GitHub Desktop.

Select an option

Save summit87/27ab9b64d4d5558feecf9760e89eacd6 to your computer and use it in GitHub Desktop.
FindPairSumInRotatedArray
package com.practice.backtracking.array;
public class FindPairSumInRotatedArray {
public static void main(String[] args) {
int[] a = {11, 15, 6, 7, 9, 10};
int sum = 16;
System.out.println(isSumExist(a,findPivot(a, 0, a.length - 1),sum));
}
private static int findPivot(int[] a, int left, int right) {
int mid = (left + right) / 2;
if (mid + 1 <= right && a[mid] > a[mid + 1]) {
return mid;
}
if (mid - 1 >= left && a[mid - 1] > a[mid]) {
return mid - 1;
}
if (a[left] < a[mid]) {
return findPivot(a, mid + 1, right);
}
if (a[left] > a[mid]) {
return findPivot(a, left, mid - 1);
}
return -1;
}
private static boolean isSumExist(int[] a, int pivot, int sum) {
int r = pivot;
int l = pivot + 1;
int count=0;
while (l != r) {
if (a[l] + a[r] == sum) {
count++;
}
if (a[l] + a[r] < sum) {
l++;
} else {
r--;
}
if (r < 0) {
r = a.length - 1;
}
if (l > a.length - 1) {
l = 0;
}
}
System.out.println(count);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment