Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions FindFirstAndLast.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
public class FindFirstAndLast {
public int[] searchRange(int[] nums, int target) {
int first = -1, last = -1, left = 0, right = nums.length - 1, mid;

// Search for the first occurrence of target
while (left <= right) {
mid = left + (right - left) / 2;

if (nums[mid] == target) {
first = mid;
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

left = 0;
right = nums.length - 1;

// Search for the last occurrence of target
while (left <= right) {
mid = left + (right - left) / 2;

if (nums[mid] == target) {
last = mid;
left = mid + 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return new int[]{first, last};
}
}
23 changes: 23 additions & 0 deletions FindMin.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class FindMin {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1, mid, min = Integer.MAX_VALUE;

while (left <= right) {
// check if sorted
if (nums[left] <= nums[right]) {
min = Math.min(min, nums[left]);
break;
}

mid = left + (right - left) / 2;
min = Math.min(min, nums[mid]);

if (nums[mid] >= nums[left]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return min;
}
}
27 changes: 27 additions & 0 deletions FindPeak.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
public class FindPeak {

public int findPeakElement(int[] nums) {
int left = 0, right = nums.length - 1, MID;
boolean leftCheck;
boolean rightCheck;

while (left <= right) {
MID = left + (right - left) / 2;
// check left side then check right side also
leftCheck = (MID == 0) || nums[MID] > nums[MID - 1];
rightCheck = (MID == nums.length - 1) || nums[MID] > nums[MID + 1];

if (leftCheck && rightCheck) {
return MID;
}

if (MID > 0 && nums[MID - 1] > nums[MID]) {
right = MID - 1;
} else {
left = MID + 1;
}
}

return -1;
}
}