Skip to content

Commit 1a59684

Browse files
author
Prashant Jain
committed
Added binary search problems
1 parent aa68665 commit 1a59684

5 files changed

Lines changed: 335 additions & 0 deletions

File tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package in.knowledgegate.dsa.binarysearch.problems;
2+
3+
/**
4+
* You are a product manager and currently leading
5+
* a team to develop a new product. Unfortunately,
6+
* the latest version of your product fails the
7+
* quality check. Since each version is developed based
8+
* on the previous version, all the versions after
9+
* a bad version are also bad.
10+
*
11+
* Suppose you have n versions [1, 2, ..., n] and
12+
* you want to find out the first bad one, which
13+
* causes all the following ones to be bad.
14+
*
15+
* You are given an API bool isBadVersion(version)
16+
* which returns whether version is bad. Implement
17+
* a function to find the first bad version. You
18+
* should minimize the number of calls to the API.
19+
*
20+
*
21+
* Example 1:
22+
* Input: n = 5, bad = 4
23+
* Output: 4
24+
* Explanation:
25+
* call isBadVersion(3) -> false
26+
* call isBadVersion(5) -> true
27+
* call isBadVersion(4) -> true
28+
* Then 4 is the first bad version.
29+
*
30+
* Example 2:
31+
* Input: n = 1, bad = 1
32+
* Output: 1
33+
*
34+
* Constraints:
35+
* 1 <= bad <= n <= 231 - 1
36+
*/
37+
public class FirstBadVersion {
38+
static int badVersion;
39+
static int TOTAL_VERSION = 500;
40+
41+
public static void main(String[] args) {
42+
FirstBadVersion versionChecker =
43+
new FirstBadVersion();
44+
badVersion = 412;
45+
System.out.println("\nbad version is:"
46+
+ versionChecker.firstBadVersionLinearSearch(TOTAL_VERSION));
47+
System.out.println("\nbad version is:"
48+
+ versionChecker.firstBadVersion(TOTAL_VERSION));
49+
}
50+
51+
public int firstBadVersion(int n) {
52+
int beg = 1, end = n;
53+
while (beg <= end) {
54+
int mid = (beg + end) / 2;
55+
if (isBadVersion(mid)) {
56+
end = mid - 1;
57+
} else {
58+
beg = mid + 1;
59+
}
60+
}
61+
return end + 1;
62+
}
63+
64+
public int firstBadVersionLinearSearch(int n) {
65+
for (int i = 1; i < n; i++) {
66+
if (isBadVersion(i)) return i;
67+
}
68+
return -1;
69+
}
70+
71+
private boolean isBadVersion(int version) {
72+
System.out.print(".");
73+
return version - badVersion >= 0;
74+
}
75+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package in.knowledgegate.dsa.binarysearch.problems;
2+
3+
/**
4+
* We are playing the Guess Game. The game is as follows:
5+
*
6+
* I pick a number from 1 to n. You have to guess
7+
* which number I picked.
8+
*
9+
* Every time you guess wrong, I will tell you
10+
* whether the number I picked is higher or lower than
11+
* your guess.
12+
*
13+
* You call a pre-defined API int guess(int num),
14+
* which returns three possible results:
15+
*
16+
* -1: Your guess is higher than the number I picked (i.e. num > pick).
17+
* 1: Your guess is lower than the number I picked (i.e. num < pick).
18+
* 0: your guess is equal to the number I picked (i.e. num == pick).
19+
* Return the number that I picked.
20+
*
21+
*
22+
* Example 1:
23+
* Input: n = 10, pick = 6
24+
* Output: 6
25+
*
26+
* Example 2:
27+
* Input: n = 1, pick = 1
28+
* Output: 1
29+
*
30+
* Example 3:
31+
* Input: n = 2, pick = 1
32+
* Output: 1
33+
*
34+
* Constraints:
35+
* 1 <= n <= 231 - 1
36+
* 1 <= pick <= n
37+
*/
38+
public class GuessNumberHigherOrLower {
39+
static int numberToGuess;
40+
41+
public static void main(String[] args) {
42+
GuessNumberHigherOrLower guesser =
43+
new GuessNumberHigherOrLower();
44+
numberToGuess = 99;
45+
System.out.println("\nnumber is:" + guesser.guessNumberNormalSearch(100));
46+
System.out.println();
47+
System.out.println("\nnumber is:" + guesser.guessNumber(100));
48+
}
49+
50+
public int guessNumber(int n) {
51+
int beg = 1, end = n;
52+
while (beg <= end) {
53+
int mid = (beg + end) / 2;
54+
int res = guess(mid);
55+
if (res == 0) return mid;
56+
if (res == -1) end = mid -1;
57+
else beg = mid + 1;
58+
}
59+
return -1;
60+
}
61+
62+
public int guessNumberNormalSearch(int n) {
63+
for (int i = 1; i <= n; i++) {
64+
if (guess(i) == 0) return i;
65+
}
66+
return -1;
67+
}
68+
69+
private int guess(int num) {
70+
System.out.print(".");
71+
if (num == numberToGuess) return 0;
72+
else if (num < numberToGuess) return 1;
73+
return -1;
74+
}
75+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package in.knowledgegate.dsa.binarysearch.problems;
2+
3+
/**
4+
* Write an efficient algorithm that searches for
5+
* a value target in an m x n integer matrix.
6+
* This matrix has the following properties:
7+
*
8+
* Integers in each row are sorted from left to right.
9+
* The first integer of each row is greater than
10+
* the last integer of the previous row.
11+
*
12+
* Example 1:
13+
* Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]],
14+
* target = 3
15+
* Output: true
16+
*
17+
* Example 2:
18+
* Input: matrix = [[1,3,5,7],[10,11,16,20],
19+
* [23,30,34,60]], target = 13
20+
* Output: false
21+
*
22+
* Constraints:
23+
* m == matrix.length
24+
* n == matrix[i].length
25+
* 1 <= m, n <= 100
26+
* -104 <= matrix[i][j], target <= 104
27+
*/
28+
public class SearchIn2DMatrix {
29+
public static void main(String[] args) {
30+
SearchIn2DMatrix search =
31+
new SearchIn2DMatrix();
32+
int[][] nums = new int[][]{{1,3,5,7},
33+
{10,11,16,20},{23,30,34,60}};
34+
System.out.println("Element status: "
35+
+ search.searchMatrix(nums, 24));
36+
}
37+
38+
public boolean searchMatrix(int[][] matrix, int target) {
39+
if (matrix == null || matrix.length == 0) return false;
40+
int m = matrix.length;
41+
int n = matrix[0].length;
42+
int tot = m * n;
43+
int beg = 0;
44+
int end = tot - 1;
45+
while (beg <= end) {
46+
int mid = (beg + end) / 2;
47+
int i = mid / n;
48+
int j = mid % n;
49+
if (matrix[i][j] == target)
50+
return true;
51+
else if (matrix[i][j] < target)
52+
beg = mid + 1;
53+
else
54+
end = mid - 1;
55+
}
56+
return false;
57+
}
58+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package in.knowledgegate.dsa.binarysearch.problems;
2+
3+
/**
4+
* There is an integer array nums sorted in ascending
5+
* order (with distinct values).
6+
*
7+
* Prior to being passed to your function, nums is
8+
* possibly rotated at an unknown pivot index
9+
* k (1 <= k < nums.length) such that the resulting
10+
* array is [nums[k], nums[k+1], ..., nums[n-1],
11+
* nums[0], nums[1], ..., nums[k-1]] (0-indexed).
12+
* For example, [0,1,2,4,5,6,7] might be rotated
13+
* at pivot index 3 and become [4,5,6,7,0,1,2].
14+
*
15+
* Given the array nums after the possible rotation
16+
* and an integer target, return the index of
17+
* target if it is in nums, or -1 if it is not in
18+
* nums.
19+
*
20+
* You must write an algorithm with O(log n) runtime
21+
* complexity.
22+
*
23+
*
24+
* Example 1: 0,1,2,3,4,5,6
25+
* Input: nums = [4,5,6,7,0,1,2], target = 0
26+
* Output: 4
27+
*
28+
* Example 2:
29+
* Input: nums = [4,5,6,7,0,1,2], target = 3
30+
* Output: -1
31+
*
32+
* Example 3:
33+
* Input: nums = [1], target = 0
34+
* Output: -1
35+
*
36+
*
37+
* Constraints:
38+
* 1 <= nums.length <= 5000
39+
* -104 <= nums[i] <= 104
40+
* All values of nums are unique.
41+
* nums is an ascending array that is possibly rotated.
42+
* -104 <= target <= 104
43+
*/
44+
public class SearchInRotatedSortedArray {
45+
public static void main(String[] args) {
46+
SearchInRotatedSortedArray search =
47+
new SearchInRotatedSortedArray();
48+
int[] nums = new int[]{4,5,6,7,0,1,2};
49+
System.out.println("Found at:"
50+
+ search.search(nums, 3));
51+
}
52+
53+
int search(int[] nums, int target) {
54+
int beg = 0, end = nums.length - 1;
55+
while (beg <= end) {
56+
int mid = (beg + end) / 2;
57+
if (nums[mid] > nums[end])
58+
beg = mid + 1;
59+
else
60+
end = mid - 1;
61+
}
62+
int shift = end + 1;
63+
64+
beg = 0;
65+
end = nums.length - 1;
66+
while(beg <= end) {
67+
int mid = (beg + end) / 2;
68+
int realMid =
69+
(mid + shift) % nums.length;
70+
if (nums[realMid] == target)
71+
return realMid;
72+
else if (nums[realMid] < target)
73+
beg = mid + 1;
74+
else
75+
end = mid - 1;
76+
}
77+
return -1;
78+
}
79+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package in.knowledgegate.dsa.binarysearch.problems;
2+
3+
/**
4+
* You are given a sorted array consisting of only
5+
* integers where every element appears exactly
6+
* twice, except for one element which appears exactly once.
7+
*
8+
* Return the single element that appears only once.
9+
* Your solution must run in O(log n) time and O(1) space.
10+
*
11+
* Example 1:
12+
* Input: nums = [1,1,2,3,3,4,4,8,8]
13+
* Output: 2
14+
*
15+
* Example 2: 0,1,2,3,4 ,5 ,6
16+
* Input: nums = [3,3,7,7,10,11,11]
17+
* Output: 10
18+
*
19+
* Constraints:
20+
* 1 <= nums.length <= 105
21+
* 0 <= nums[i] <= 105
22+
*/
23+
public class SingleElementInASortedArray {
24+
public static void main(String[] args) {
25+
SingleElementInASortedArray finder =
26+
new SingleElementInASortedArray();
27+
int[] nums = new int[]{3,3,7,7,10,11,11};
28+
System.out.println("Duplicate is:"
29+
+ finder.singleNonDuplicate(nums));
30+
}
31+
32+
public int singleNonDuplicate(int[] nums) {
33+
int left = 0, right = nums.length - 1;
34+
while (left < right) {
35+
int mid = left + (right - left) / 2;
36+
if ((mid % 2 == 0 && nums[mid] == nums[mid+1]) ||
37+
(mid % 2 == 1 && nums[mid] == nums[mid -1])) {
38+
left = mid + 1;
39+
} else {
40+
right = mid - 1;
41+
}
42+
}
43+
return nums[left];
44+
}
45+
}
46+
47+
48+

0 commit comments

Comments
 (0)